带链的栈
#include "stdafx.h"
#include "iostream"
using namespace std;
struct Node
{
int data;
Node *next;
};
class Link_stack
{
public:
Link_stack(); //初始化栈
void prt_Linkstack(); //输出栈
int flag_Linkstack(); //检测栈
void push_Linkstack(); //入栈
int pop_Linkstack();//出栈
int read_Linkstack();//读栈顶
private:
Node *top;
};
Link_stack::Link_stack()
{
top=NULL;
return ;
}
void Link_stack::prt_Linkstack()
{
Node *p;
p=top;
if (p==NULL)
{
cout<<"空栈"<<endl;
return ;
}
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
return;
}
int Link_stack::flag_Linkstack()
{
if (top==NULL)
return 0; //空栈
return 1;
}
void Link_stack::push_Linkstack()
{
int x;
cin>>x;
Node *p;
p=new Node ;
p->data=x;
p->next=top;
top=p;
return;
}
int Link_stack::pop_Linkstack()
{
int x;
Node *p;
if(top==NULL)
{
cout<<"空栈"<<endl;
return 0;
}
p=top;
x=p->data;
top=p->next;
delete p;
return x;
}
int Link_stack::read_Linkstack()
{
if (top==NULL)
{
cout<<"空栈"<<endl;
return 0;
}
return top->data;
}
int _tmain(int argc, _TCHAR* argv[])
{
Link_stack s;
cout<<"入栈*************"<<endl;
s.push_Linkstack();
s.push_Linkstack();
s.push_Linkstack();
s.push_Linkstack();
s.prt_Linkstack();
cout<<"*************"<<endl;
if (s.flag_Linkstack())
cout<<"栈顶:"<<s.read_Linkstack()<<endl;
cout<<"出栈*************"<<endl;
if (s.flag_Linkstack())
cout<<"退栈:"<<s.pop_Linkstack()<<endl;
s.prt_Linkstack();
cout<<"出栈*************"<<endl;
if (s.flag_Linkstack())
cout<<"退栈:"<<s.pop_Linkstack()<<endl;
s.prt_Linkstack();
cout<<"*出栈************"<<endl;
if (s.flag_Linkstack())
cout<<"退栈:"<<s.pop_Linkstack()<<endl;
s.prt_Linkstack();
return 0;
}
栈
最新推荐文章于 2023-12-08 18:02:14 发布