数据结构____栈的顺序结构表示
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 0
#define OK 1
#define ERROR 0
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &s)
{
s.base=(int *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!s.base)exit(OVERFLOW);
s.top = s.base;
s.stacksize=STACK_INIT_SIZE;
return OK;
}
Status GetTop(SqStack s,SElemType &e)
{
if(s.top = s.base) return ERROR;
e = *(s.top-1);
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;
}
int Stacklength(SqStack s)
{
int count = 0;
while(s.top!=s.base)
{
count++;
s.top--;
}
return count;
} //返回栈s的元素个数
Status StackTraverse(SqStack s)
{
//从栈顶到栈底依次输出栈中的每一个元素
SElemType *p = (SElemType *)malloc(sizeof(SElemType));//临时存放栈顶元素
p=s.top;
if(s.top==s.base)
printf("The Stack is Empty!");
else{
printf("The Stack is:");
p--;
while(p>=s.base)
{
printf("%d",*p);
p--;
}
}
printf("\n");
return OK;
}
int main ()
{
int a;
SqStack s;
SElemType x, e;
if(InitStack(s))//判断顺序表是否创建成功
{
printf("A stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d",&x);
if(!Push(s,x)) printf("Push is error!\n");
else printf("The Element %d is Successfullllllly Pushed!\n",x);
break;
case 2:if(Pop(s,e)) printf("Get top ERROR!\n");
else printf("The Element %d is Successfully Poped!\n",e);
break;
case 3:if(GetTop(s,e)) printf("Get Top Error!\n");
else printf("The Top Element is %d!\n",e);
break;
case 4:printf("The Length of the Stack is %d!\n",Stacklength(s));
break;
case 5:StackTraverse(s);
break;
case 0:return 1;
}
}
return 0;
}