WEB开发网
开发学院软件开发数据结构 数据结构教程 第十七课 实验三:栈的表示与实现及... 阅读

数据结构教程 第十七课 实验三:栈的表示与实现及栈的应用

 2007-05-16 11:56:25 来源:WEB开发网   
核心提示:这里是实现栈的头文件#include "simuc.h"#define OVERFLOW -1#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int Status;struct STACK{ SElemType *base;

这里是实现栈的头文件

#include "simuc.h"

#define OVERFLOW -1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef int Status;

struct STACK
{
  SElemType *base;
  SElemType *top;
  int stacksize;
};

typedef struct STACK SqStack;
typedef struct STACK *pSqStack;

Status InitStack(SqStack  **S);
Status DestroyStack(SqStack *S);
Status ClearStack(SqStack *S);
Status StackEmpty(SqStack S);
int StackLength(SqStack S);
SElemType GetTop(SqStack S);
Status Push(SqStack *S,SElemType e);
Status Pop(SqStack *S,SElemType *e);
Status StackTraverse(SqStack S,Status (*visit)());

Status InitStack(SqStack **S)
{
  (*S)=(SqStack *)malloc(sizeof(SqStack));
  (*S)->base=(SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
  if(!(*S)->base)exit(OVERFLOW);
  (*S)->top=(*S)->base;
  (*S)->stacksize=STACK_INIT_SIZE;
  return OK;
}

Status DestroyStack(SqStack *S)
{
 free(S->base);
 free(S);
}

Status ClearStack(SqStack *S)
{
  S->top=S->base;
}

Status StackEmpty(SqStack S)
{
  if(S.top==S.base) return TRUE;
  else
    return FALSE;
}

int StackLength(SqStack S)
{
  int i;
  SElemType *p;
  i=0;
  p=S.top;
  while(p!=S.base)
    {p++;
     i++;
    }
}

SElemType GetTop(SqStack S)
{
  if(S.top==S.base) return ERROR;
  return *(S.top-1);
}

Status Push(SqStack *S,SElemType e)
{
 /*
  if(S->top - S->base>=S->stacksize)
   {

     S->base=(SElemType *) realloc(S->base,
	    (S->stacksize + STACKINCREMENT) * sizeof(SElemType));
     if(!S->base)exit(OVERFLOW);
     S->top=S->base+S->stacksize;
     S->stacksize += STACKINCREMENT;
   }
  */

  *(S->top++)=e;
  return OK;
}

Status Pop(SqStack *S,SElemType *e)
{
  if(S->top==S->base) return ERROR;
  *e=*(--(S->top));
  return OK;
}


Status StackTraverse(SqStack S,Status (*visit)())
{
  while(S.top>S.base)
     visit(--S.top);
}

上一页  1 2 3 

Tags:数据结构 教程 第十七

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接