顺序栈的存储结构是顺序表,使用栈存储结构操作数据元素必须遵守 "先进后出" 的原则,且进栈出栈都在表的同一侧。
栈的基本操作:
1、进栈:初始状态为空栈,所以栈帧指向数组外。
依次向栈中加入元素,栈帧也跟着移动,指向栈顶
……
代码:
int push(int*a,int top,int elem)
{
a[++top]=elem;
return top;
}
2、出栈:
……
代码:
int pop(int *a,int top)
{
if(top==-1)
{
printf("空栈n");
return -1;
}
printf("弹栈元素:%dn",a[top]);
top--;
return top;
}
完整代码:
#includeint push(int*a,int top,int elem) { a[++top]=elem; return top; } int pop(int *a,int top) { if(top==-1) { printf("空栈n"); return -1; } printf("弹栈元素:%dn",a[top]); top--; return top; } int main() { int a[100]; int top=-1; top=push(a, top, 1); top=push(a, top, 2); top=push(a, top, 3); top=push(a, top, 4); top=pop(a, top); top=pop(a, top); top=pop(a, top); top=pop(a, top); top=pop(a, top); return 0; }
输出结果:



