栈采用顺序存储结构,实现如下任务:
(1)初始化顺序栈InitStack_Sq(SqStack &S);
(2)扩充空间Increment(SqStack &S);
(2)入栈Push_Sq(SqStack &S,ElemType e);
(4)取栈顶元素GetTop_Sq(SqStack S,ElemType &e);
(5)出栈Pop_Sq(SqStack &S,ElemType &e);
(6)输出顺序栈元素TraverseStack_Sq(SqStack S);
(7)销毁顺序栈DestroyStack_Sq(SqStack S)。
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 5
typedef struct
{
ElemType *elem;
int top;
int stacksize;
}SqStack;
void Error(char *s)
{
printf("%s\n",s);
exit(1);
}
void InitStack_Sq(SqStack &S) //初始化
{
S.elem = new ElemType[STACK_INIT_SIZE];
if(!S.elem) Error("Overflow!");
S.top = -1;
S.stacksize = STACK_INIT_SIZE;
}
void Increment(SqStack &S) //扩充空间
{
ElemType *ns;
ns = new ElemType[S.stacksize+STACK_INCREMENT];
if(!ns) Error("Overflow!");
for(int i = 0;i<=S.top;i++)
{
ns[i]=S.elem[i];
}
delete []S.elem;
S.elem = ns;
S.stacksize = S.stacksize+STACK_INCREMENT;
}
void Push_Sq(SqStack &S,ElemType e) //入栈
{
if(S.top==(S.stacksize-1)) Increment(S);
S.elem[++S.top]=e;
}
void GetTop_Sq(SqStack S,ElemType &e) //取栈顶元素
{
if(S.top!=-1)
{
e=S.elem[S.top];
}
else
{
Error("Stack Empty!");
}
}
void Pop_Sq(SqStack &S,ElemType &e) //出栈
{
if(S.top!=-1)
{
e=S.elem[S.top];
S.top=S.top-1;
}
else
{
Error("Stack Empty!");
}
}
void TraverseStack_Sq(SqStack S) //输出顺序栈元素
{
int i=0;
while(i!=S.top+1)
{
printf("%d ",S.elem[i]);
i++;
}
printf("\n");
}
void DestroyStack_Sq(SqStack S) //销毁顺序栈
{
delete []S.elem;
S.top=-1;
S.stacksize=0;
}
int main()
{
SqStack S;
ElemType n,e;
int i;
InitStack_Sq(S);
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&e);
Push_Sq(S,e);
}
printf("CreateStack_Sq: ");
TraverseStack_Sq(S);
GetTop_Sq(S,e);
printf("Top element is %d\n",e);
printf("SqStack after GetTop: ");
TraverseStack_Sq(S);
Pop_Sq(S,e);
printf("SqStack after Pop: ");
TraverseStack_Sq(S);
DestroyStack_Sq(S);
return 0;
}