#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Listack;
//初始化栈
void Init(Listack * &s)
{
s=(Listack *)malloc(sizeof(Listack));
s->next=NULL;
}
//销毁栈
void Destroy(Listack * &s)
{
Listack *p=s,*q=s->next;
while(q!=NULL)
{
free(p);
p=q;
q=q->next;
}
free(p);
}
//判断空栈
void Is_empty(Listack * &s)
{
if(s->next==NULL) cout<<"栈为空"<<endl;
else cout<<"栈非空"<<endl;
}
//进栈
void Push(Listack * &s,int e)
{
Listack *t;
t=(Listack *)malloc(sizeof(Listack));
t->data=e;
t->next=s->next;
s->next=t;
cout<<"元素"<<e<<"进栈"<<endl;
}
//出栈
void Pop(Listack * &s)
{
if(s->next==NULL)
{
cout<<"栈为空"<<endl;
return ;
}
Listack *t;
t=s->next;
s->next=t->next;
cout<<"栈顶元素"<<t->data<<"出栈"<<endl;
free(t);
}
void Get_top(Listack * &s)
{
if(s->next==NULL)
{
cout<<"栈为空"<<endl;
return ;
}
cout<<"栈顶元素为:"<<s->next->data<<endl;
}
//遍历栈
void Display(Listack *s)
{
if(s->next==NULL)
{
cout<<"栈为空"<<endl;
return ;
}
while(s->next!=NULL)
{
cout<<s->next->data<<endl;
s=s->next;
}
}
int main()
{
Listack *s;
int choose,ans;
Init(* &s);
cout<<"1.进栈 2.出栈"<<endl;
cout<<"3.判断空栈 4.取栈顶元素"<<endl;
cout<<"5.遍历栈的元素"<<endl;
cin>>choose;
while(choose)
{
switch(choose)
{
case 1:cout<<"输入进栈元素"<<endl;
cin>>ans;
Push(* &s,ans);
break;
case 2:Pop(* &s);break;
case 3:Is_empty(* &s);break;
case 4:Get_top(* &s);break;
case 5:Display(* &s);
}
cin>>choose;
}
Destroy(* &s);
return 0;
}
栈的简单操作(栈的链式存储)
最新推荐文章于 2023-12-03 15:58:55 发布