棧是一種限制性的線性結構,對於一個棧,一般會有出棧、入棧、獲取棧頂元素集中操作。它只能對棧頂進行操作,對於棧內的元素不能進行任何操作。想象成一個線性表的話,就是只能在一端進行插入或者刪除的操作,並且不能遍歷。對於一個棧來說,遍歷的話就只能讓所有元素出棧,直到變爲空棧。
棧的順序存儲,就是直接設計好棧的最大尺寸,然後使用一個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;
}