数据结构之栈
栈又名堆栈,是一种线性表结构,受限制与只能再尾部进行插入和删除操作,所以它是先进后出的一个算法,生活中有很多案例都是用到了栈这样一个结构。
下面是关于顺序栈的简单操作
#include<iostream>
using namespace std;
#define MaxSize 50
typedef char ElemType;
typedef struct SqStack{
ElemType data[MaxSize];
int top;
}SqStack;
//栈空条件是S.top=-1,而栈满的条件是S.top==MaxSize-1,栈长等于S.top+1;
//初始化栈
void InitStack(SqStack &s){
s.top=-1;//初始化栈顶指针
}
//判定栈是否空
bool IsEmpty(SqStack s){
if(s.top==-1)
return true;//空
else
return false;//非空
}
//数据进栈
bool Push(SqStack &s,ElemType e){//加上引用符号,因为数据是要能够返回原来的地址的
if(s.top==MaxSize-1){
return false;//说明栈满,不能在添加数据了,报错
}
s.data[++s.top]=e;//因为栈顶指针一开始是-1,要让他先加1在进行赋值
return true;
}
//数据出栈
bool Pop(SqStack &s,ElemType &e){//要将弹出的元素值输出,所以要用引用类型保存数据
if(s.top==-1){
return false;//栈空
}
e=s.data[s.top--];//因为是取数,取完栈内元素减1,栈顶指针就要减1.
//e=s.data[s.top];
//s.top=s.top-1; 两者等价
}
//读书栈顶元素
bool getTop(SqStack s,ElemType &e){
if(s.top==-1){
return false;
}
e=s.data[s.top];
return true;
}
bool PushOut(SqStack &s){
if(s.top==-1){
return false;
}
while(s.top!=-1){
cout<<s.data[s.top--]<<" ";
}
cout<<endl;
}
int main(){
SqStack s;
InitStack(s);
int n;
char a=97;
ElemType e;
cin>>n;
cout<<"入栈:";
while(n>0){
Push(s,a);
cout<<a<<" ";
a++;
n--;
}
Pop(s,e);
cout<<"弹出栈顶元素:"<<e<<endl;
getTop(s,e);
cout<<"栈顶元素:" ;
cout<<e<<endl;
cout<<"出栈:" ;
PushOut(s);
return 0;
}
同时还有链栈
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct Linknode{
ElemType data;
struct Linknode *next;
}Linknode,*stack;
//初始化链栈
void init(stack &s){
s=NULL;//将栈顶指针置空
}
bool push(stack &s,ElemType e){
//创建新结点,并且移动
stack node=new Linknode();
node->next=s;
node->data=e;
s=node;
return true;
bool pop(stack &s,ElemType &e){
}
stack p;
if(s->next==NULL){
return false;//说明栈内没有数据,若有一定不为空
}
e=s->data;
p=s;
s=s->next;//栈顶结点向后移
delete p;//删除无效的结点
return true;
}
void output(stack s){
while(s!=NULL){
cout<<s->data<<" ";
s=s->next;
}
cout<<endl;
}
int main(){
stack s;
init(s);
int i;
cin>>i;
while(i>0){
push(s,i);
cout<<i<<" ";
i--;
}
cout<<endl;
output(s);
return 0;
}