栈:LIFO 后进先出。
顺序栈实现代码:
#include<stdio.h>
#define MaxSize 10
typedef struct{
int data[MaxSize];
int top;
}SqStack;
SqStack InitStack(SqStack S)
{
S.top=-1;
return S;
}
SqStack Push(SqStack S,int e)
{
if(S.top>=MaxSize-1)
printf("栈已满\n");
S.top++;
S.data[S.top]=e;
return S;
}
SqStack Pop(SqStack S)
{
if(S.top==-1)
printf("栈空无法出栈\n");
S.top--;
return S;
}
int GetTop(SqStack S)
{
if(S.top==-1)
printf("栈空无法获得栈顶元素\n");
return S.data[S.top];
}
void StackDisplay(SqStack S)
{
int i=0;
while(S.top!=-1)
{
printf("%d",GetTop(S));
S=Pop(S);
i++;
}
S.top+=i;
printf("\n");
}
int main()
{
int a[5]={1,2,3,4,5};
int i;
SqStack S;
S=InitStack(S);
for(i=0;i<sizeof(a)/sizeof(int);i++)
{
S=Push(S,a[i]);
}
StackDisplay(S);
return 0;
}
运行结果: