栈是一种后进先出的数据结构。
///将一个数组逆时针旋转90°不就相当于一个顺序栈嘛
#include<cstdio>
#include<iostream>
using namespace std;
#define MAXSIZE 50
typedef struct
{
int data[MAXSIZE];
int top;///栈顶指针
}SqStack;
void InitStack(SqStack &S)///栈的初始化。
{
S.top=-1;
}
bool StackEmpty(SqStack S)
{
if(S.top==-1) return true;
else return false;
}
bool Push(SqStack &S,int x)///入栈
{
if(S.top==MAXSIZE-1) return false;
S.data[++S.top]=x;
return true;
}
bool Pop(SqStack &S,int &x)///出栈,并用x返回出栈的元素
{
if(S.top==-1) return false;///栈空,无元素可出,报错
x=S.data[S.top--];
return true;
}
bool GetTop(SqStack S,int &x)
{
if(S.top==-1) return false;///栈空,无元素可读,报错
x=S.data[S.top];
return true;
}
void Stack_Traverse(SqStack S)///遍历栈
{
int i,j;
if(S.top==-1) return ;///栈空,结束函数
for(i=0;i<=S.top;i++)
cout<<S.data[i]<<" ";
cout<<endl;
}
int main()
{
int x;
SqStack S={{1,2,3,4,5,6,7,8,9,10},9};///创建并且初始化一个栈
if(StackEmpty(S)) cout<<"栈为空"<<endl;
else cout<<"栈不为空"<<endl;
if(Push(S,99)) cout<<"进栈成功"<<endl;
else cout<<"进栈失败"<<endl;
Stack_Traverse(S);
if(Pop(S,x)) cout<<"出栈成功"<<endl;
else cout<<"出栈失败"<<endl;
Stack_Traverse(S);
return 0;
}
本文深入解析了栈这种后进先出(LIFO)数据结构的基本操作,包括初始化、判断是否为空、入栈、出栈及遍历等核心功能,并通过C++代码实现了一个顺序栈,演示了栈的使用。
1058

被折叠的 条评论
为什么被折叠?



