//栈的顺序存储结构和操作
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int ElemType;
//① 初始化栈S为空
struct Stack{
ElemType *stack; //存栈元素
int top; //存栈顶元素的下标位置
int MaxSize;
};
void InitStack(Stack& S)
{
//初始设置栈的空间大小为10个元素位置
S.MaxSize = 10;
//动态存储空间分配,若分配失败则退出运行
S.stack = new ElemType[S.MaxSize];
if(!S.stack){
cerr<<"动态存储分配失败"<<endl;
exit(1);
}
//初始置栈为空
S.top = -1;
}
//② 元素item进栈,即插入到栈顶
void Push(Stack& S, ElemType item )
{
//若栈的空间用完则自动扩大2倍空间,原有栈内容不变
if(S.top == S.MaxSize-1){
int k = sizeof(ElemType);
S.stack = (ElemType*)realloc(S.stack, 2*S.MaxSize*k);
S.MaxSize = 2*S.MaxSize;
}
//栈顶指针后移一个位置
S.top++;
S.stack[S.top] = item; //将新元素插入到栈顶
}
//③ 删除栈顶元素并返回
ElemType Pop(Stack& S)
{
//若栈空则退出运行
if(S.top == -1){
cerr<<"Stack is empty!"<<endl;
exit(1);
}
//栈顶指针减一表示退栈
S.top--;
//返回原栈顶的元素
return S.stack[S.top+1];
}
//④ 读取栈顶元素的值
ElemType Peek(Stack& S)
{
//若栈空则退出运行
if(S.top == -1)
{
cerr<<"Stack is empty!"<<endl;
exit(1);
}
//返回栈顶元素的值
return S.stack[S.top];
}
//⑤ 判断s是否为空,若是则返回true,
bool EmptyStack(Stack& S){
return S.top == -1;
}
//⑥ 清除栈S中的所有元素,释放动态存储空间
void ClearStack(Stack& S){
if(S.stack){
delete []S.stack;
S.stack = 0;
}
S.top = 1;
S.MaxSize = 0;
}
int main(){
Stack s;
InitStack(s);
int a[8] = {3,8,5,17,9,30,15,22};
int i ;
for(i = 0; i<8; i++) Push( s, a[i]);
cout<<Pop(s);
cout<<' '<<Pop(s)<<endl;
Push(s, 68);
cout<<Peek(s);
cout <<' '<<Pop(s)<<endl;
while (!EmptyStack(s))
cout <<Pop(s)<<' ';
cout <<endl;
ClearStack(s);
}
栈的存储结构和操作
最新推荐文章于 2023-02-25 21:31:37 发布