链栈

来源:互联网 发布:python 可视化 编辑:程序博客网 时间:2024/05/20 05:56

#include <iostream.h>

#include <stdio.h>
#include <malloc.h>
typedef int Elemtype;

typedef struct Stacknode
{
Elemtype data;
struct Stacknode *next;
//struct Stacknode *top;
}Stacknode;
typedef struct 
{
Stacknode *top;
}LinkStack;

void Initial(LinkStack*s)
{
Stacknode *p;
p=new Stacknode;
//p=(Stacknode)malloc(sizeof(Stacknode));
if(p==NULL)
{
cout<<"分配存储失败!"<<endl;
return ;
}
p->next=NULL;
s->top=p;
}
int IsEmpty(LinkStack*s)
{
return s->top->next==NULL;
}

void Push(LinkStack *s,Elemtype e)
{
Stacknode *p;
p=new Stacknode;
if(p==NULL)
{
cout<<"分配存储失败!"<<endl;
return ;
}
p->data=e;
p->next=s->top->next;
s->top->next=p;
}

void  Pop(LinkStack *s)
{
Elemtype temp;
Stacknode *p;
if(IsEmpty(s))
{
cout<<"空栈!"<<endl;
return ;
}
p=s->top->next;
temp =p->data;
s->top->next=p->next;
delete p;
cout<<temp;
}

Elemtype Gettop(LinkStack *s)
{
Stacknode *p;
if(IsEmpty(s))
{
cout<<"空栈!"<<endl;
return 0;
}
p=s->top->next;
return p->data;
}

void MakeEmpty(LinkStack *s)
{
Stacknode *p,*q;
p=s->top->next;
while (p!=NULL)
{
q=p;
p=p->next;
delete p;
}
s->top->next=NULL;
}

void Destroy(LinkStack *s)
{
Stacknode *p,*q;
p=s->top;
while (p!=NULL)
{
q=p;
p=p->next;
delete p;
}
    s->top=NULL;
}

void main()
{
int k=1,m,x;
LinkStack *hs;
Stacknode *ps;
Elemtype e;
hs=new LinkStack;
ps=new Stacknode;
cout<<"1.元素进栈"<<endl<<"2.元素出栈"<<endl<<"3.读取栈顶元素"<<endl<<"4.栈置空"<<endl<<"5.退出"<<endl;
cin>>x;
while(k)
{
cout<<"请选择1--5"<<endl;
cin>>m;
switch(m)
{
case 1:
{
cout<<"输入元素,入栈"<<endl;
cin>>e;
Push(hs,e);
break;
}
case 2:
{Pop(hs);
cout<<e<<endl;
break;}
case 3:
{cout<<"取出栈顶元素"<<endl;
x=Gettop(hs);
break;}
case 4:
{
cout<<"栈置空!"<<endl;
MakeEmpty(hs);
cout<<endl;
break;}
case 5:
return ;
default :
return;
}
}
cout<<"继续运行吗Y(1)/N(0):";
cin>> k;
if(!k)
return ;
}
原创粉丝点击