栈是一种限制性的线性结构,对于一个栈,一般会有出栈、入栈、获取栈顶元素集中操作。它只能对栈顶进行操作,对于栈内的元素不能进行任何操作。想象成一个线性表的话,就是只能在一端进行插入或者删除的操作,并且不能遍历。对于一个栈来说,遍历的话就只能让所有元素出栈,直到变为空栈。
栈的顺序存储,就是直接设计好栈的最大尺寸,然后使用一个top变量,来标记栈顶位置,然后在栈顶进行出栈入栈的操作,删除元素后内存没有释放,元素依然存在。只是在逻辑上,这一个元素已经不属于这个栈了。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
using namespace std;
typedef int ElemType;
typedef struct SqStack{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S); //构造顺序栈
bool StackEmpty(SqStack &S); //判断是否栈为空
bool Push(SqStack &S,ElemType e); //入栈操作
bool Pop(SqStack &S,ElemType &e); //出栈操作
bool GetTop(SqStack S,ElemType &e); //获取栈顶元素
int main()
{
while(true){
int n,a,t;
SqStack S;
InitStack(S);
cin >> n;
while(n--){
cin >> a;
Push(S,a);
GetTop(S,t);
cout << t << endl;
}
for(int i=0;i<3;i++){
Pop(S,a);
GetTop(S,t);
cout << t << endl;
}
}
return 0;
}
void InitStack(SqStack &S){
S.top=-1;
}
bool StackEmpty(SqStack &S){
if(S.top==-1)
return true;
return false;
}
bool Push(SqStack &S,ElemType e){
if(S.top==MaxSize-1)
return false;
S.top++;
S.data[S.top]=e;
return true;
}
bool Pop(SqStack &S,ElemType &e){
if(S.top==-1)
return false;
e=S.data[S.top];
S.top--;
return true;
}
bool GetTop(SqStack S,ElemType &e){
if(S.top==-1)
return false;
e=S.data[S.top];
return true;
}