栈的基本操作(采用顺序存储结构)

关于栈的基本操作,记录一下,方便以后查看。包括栈的初始化、入栈、出栈、清空栈、销毁栈、获取已入栈元素个数

#include 
#include 

#define TRUE 1
#define FALSE 0
#define ERROR -1
#define STACKINITSIZE 20
#define STACKADDSIZE 5

typedef int ElemType;
typedef int Status;
typedef struct 
{
  ElemType *top;
  ElemType *base;
  int stackSize;
} sqStack;

Status InitStack(sqStack *s);
Status PushStack(sqStack *s,ElemType e);
Status PopStack(sqStack *s,ElemType *e);
Status ClearStack(sqStack *s);
Status DestroyStack(sqStack *s);
int GetStackLen(sqStack *s);
void my_err(char *s);

int main(int argc,char *argv[])
{
  sqStack s;
  Status result;
  result=InitStack(&s);
  if(result==ERROR)
    {
      my_err("InitStack return Error.");
    }
  int i;
  for(i=0;i<47;i++)
    {
      result=PushStack(&s,i);
      if(result==ERROR)
    {
      my_err("PushStack return Error.");
    }
    }
  ElemType e; 
  for(i=0;i<40;i++)
    {
      result=PopStack(&s,&e);
      if(result==FALSE)
    {
      printf("The stack has no value.\n");
      break;
    }
      if(result==TRUE)
    {
      printf("%d,",e);
    }
    }
  printf("\nStack length:%d\n",GetStackLen(&s));
  ClearStack(&s);
  DestroyStack(&s);
  exit(0);
}

//初始化栈
Status InitStack(sqStack *s)
{
  s->base=(ElemType *)malloc(STACKINITSIZE*sizeof(ElemType));
  if(!s->base)
    return ERROR;
  s->top=s->base;
  s->stackSize=STACKINITSIZE;
  return TRUE;
}

//入栈
Status PushStack(sqStack *s,ElemType e)
{
  if(s->top-s->base>=s->stackSize)//当栈空间大小不足时,动态增长栈空间
    {
      s->base=(ElemType *)realloc(s->base,(STACKADDSIZE+s->stackSize)*sizeof(ElemType));
      if(!s->base)
    return ERROR;
      s->top=s->base+s->stackSize;
      s->stackSize+=STACKADDSIZE;
    }
  *(s->top)=e;
  s->top++;
  return TRUE;
}

//出栈
Status PopStack(sqStack *s,ElemType *e)
{
  if(s->top==s->base)
    return FALSE;
  (*e)=*(--s->top);
  return TRUE;
}

//销毁栈
Status DestroyStack(sqStack *s)
{
  free(s->base);
  s->base=s->top=NULL;
  s->stackSize=0;
  return TRUE;
}

//清空栈
Status ClearStack(sqStack *s)
{
  s->top=s->base;
  return TRUE;
}

//获取栈中已有数据的长度
int GetStackLen(sqStack *s)
{
  return s->top-s->base; //注意:地址指针相减,结果并不是地址差,而是实际元素的差值。
}

void my_err(char *s)
{
  perror(s);
  exit(1);
}


你可能感兴趣的:(数据结构与算法)