题目:
- 建立一个顺序栈,1,2,3入栈。
- 输出栈顶元素。
- 4,5入栈
- 将栈中所有元素出栈,并输出
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
typedef int ElemType;
typedef struct{ //顺序栈的数据类型
ElemType *base;
ElemType *top;
int stacksize;
}Stack;
int Init(Stack &S){
S.base = new ElemType[MAXSIZE];
if(!S.base) exit(-2);
S.top = S.base;
S.stacksize = MAXSIZE;
return 1;
}
int Push(Stack &S, ElemType x){
if(S.top - S.base == S.stacksize){
cout<<"栈空间已满!";
return 0;
}
*S.top++ = x;
return 1;
}
int Pop(Stack &S, ElemType &e){
if(S.base == S.top){
cout<<"栈空!";
return 0;
}
e = *--S.top;
return 1;
}
ElemType GetTop(Stack S){
if(S.base != S.top){
return *(S.top - 1);
}
}
int main(){
Stack A;
ElemType e;int x;
Init(A); //初始化栈
Push(A, 1); //1,2,3依次入栈
Push(A, 2);
Push(A, 3);
cout<<"栈顶元素:"<<GetTop(A)<<endl; //输出栈顶元素
Push(A, 4); //4,5依次入栈
Push(A, 5);
cout<<"栈中元素依次出栈:"<<endl; //将栈中元素依次出栈,并输出
while(Pop(A, e)){
cout<<e<<" ";
}
}