顺序栈的实现

#include <stdio.h>
#include<stdlib.h>

#define LIST_INIT_SIZE          100  
#define LISTINCREMENT           10  

//函数返回值类型定义  
typedef enum { ERROR=0, OK=1,TRUE=1, FALSE = 0, OVERFLOW=-1, UNDERFLOW=-2 } Status;
 
//数据元素类型定义  
typedef int ElemType;     

typedef struct{
 ElemType   *base;                  //栈的存储空间的基地址,即栈底指针
 ElemType   *top;                   //栈顶指针
 int         maxsize;                //栈当前分配的存储容量
}SqStack;

Status visit( ElemType e )
{
 printf("e=%d\n",e);

 return OK;
}
Status InitStack( SqStack &S )   //构造一个空栈S
{
 S.base=(ElemType * )malloc( LIST_INIT_SIZE * sizeof(ElemType));
 if (!S.base) exit(OVERFLOW);    //存储分配失败
 S.top = S.base;                  //栈顶指针也指向栈底,意味着栈为空
 S. maxsize = LIST_INIT_SIZE;
 return OK;
}

Status ListEmpty( SqStack S )//判断是否为空
{
 if( S.top == S.base )
  return OK;

 return ERROR;
}

int  ListLength( SqStack &S )//获取顺序栈的长度
{
 return S.top-S.base;
}

Status Push ( SqStack &S, ElemType e )
{
 if ( S.top -S.base == S. maxsize) //栈满,追加存储空间
 {
     ElemType *newbase;
  newbase=( ElemType *) realloc( S.base, ( S. maxsize + LISTINCREMENT) * sizeof( ElemType ));
  if(!newbase) exit (OVERFLOW);       //存储分配失败
  S.base = newbase;
  S.top=S.base + S. maxsize;            //确定新栈的栈顶指针的位置
  S. maxsize += LISTINCREMENT;    //栈的最大容量增加
 }
 *S.top++=e;                           //插入栈顶元素,且栈顶指针增加
 return OK;
}

Status Pop( SqStack &S, ElemType &e )//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK,否则返回ERROR
{
 if ( S.top == S.base )
  return ERROR;
 e =* --S.top;         //e返回栈顶元素值,- -S.top表示删除栈顶元素
 return OK;
}

Status GetTop(SqStack S, ElemType &e)//若栈不空,则用e返回S的栈顶元素,并返回OK,否则返回ERROR
{
 if ( S.top == S.base )
  return ERROR;
 e =*( S.top -1 );                  //e返回栈顶元素值
 
 return OK;
}

Status StackTraverse( SqStack S, Status (*visit)(ElemType)) //若栈不空,则使用visit函数遍历栈的元素并返回OK,否则返回ERROR
{
 ElemType *p;
 if (S.top == S.base)
  return ERROR;
 p=S.top;                        //p指向栈顶
 while( p>S.base )
  visit(* --p);      //通过循环对栈的元素遍历

 return OK;
}

Status ClearList( SqStack &S )   //清空栈
{
 ElemType e;
 while( Pop(S, e) != ERROR );
 return OK;
}  

Status DestroyStack( SqStack &S )
{
 free( S.base );

 S.base = NULL;
 return OK;
}

posted on 2012-10-16 10:17  Eternal Code  阅读(286)  评论(0编辑  收藏  举报