棧的建立以及使用

stack.h

typedef int Status;
typedef int SElemType;


#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10


typedef struct 
{
   SElemType *base;
   SElemType *top;
   int stacksize;
}SqStack;


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


stack.cpp

#include "StdAfx.h"
#include "stack.h"


Status InitStack(SqStack &S)
{
  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)
{
   S.top=S.base=NULL;
   S.stacksize=0;
   free(S.base);
   return OK;
}


Status ClearStack(SqStack &S)
{
   S.top=S.base;
   S.stacksize=0;
   return OK;   
}


Status StackEmpty(SqStack S)
{
    if(S.base==S.top)
  return OK;


   else 
  return ERROR;  
}


int StackLength(SqStack S)
{
   SElemType sum;
   sum=S.stacksize;
   return sum;
}


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


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;
}

主文件:

// stack.cpp : Defines the entry point for the console application.
//


#include "StdAfx.h"
#include "stack.h"


int main()
{
//printf("Hello World!\n");
    SqStack S;
SElemType e,a,i,b;
a=InitStack(S);
printf("-----------------------------\n");
printf("輸入數據:\n");
for(i=1;i<=5;i++)
{
        scanf("%d",&b);
        a=Push(S,b);
}
printf("\n");
printf("-----------------------------\n");
printf("輸出結果爲:\n");
    for(i=1;i<=5;i++)
{ a=Pop(S,e);
printf("%d ",e);
}


printf("\n");
printf("-----------------------------\n");


return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章