/*
* @Description:
* @版本: 2.0
* @作者: jianwen
* @Date: 2019-11-03 10:12:36
* @LastEditors: jianwen
* @LastEditTime: 2019-11-03 10:45:35
*/
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class LinkStack
{
public:
LinkStack() //构造函数
{
top=NULL;
}
~LinkStack(); //析构函数
void Push(int x); // 将x入栈
int Pop(); //弹出栈顶元素
int GetTop() //获取栈顶元素,但不删除
{
if(top!=NULL)
return top->data;
}
bool Empty() //判断栈是否为空
{
if(top==NULL)
return 1;
else
return 0;
}
private:
Node *top;
};
LinkStack::~LinkStack()
{
Node *p;
while(top!=NULL)
{
p=top;
top=top->next;
delete p;
}
}
void LinkStack::Push(int x)
{
Node *s=new Node;
s->data=x;
s->next=top;
top=s;
}
int LinkStack::Pop()
{
Node *p;
int x;
if(top==NULL)cout<<"stack is empty"<<endl;
else
{
x=top->data;
p=top;
top=p->next;
delete p;
return x;
}
}
int main()
{
LinkStack s;
s.Push(5);
s.Push(6);
s.Push(9);
cout<<s.GetTop()<<endl;
cout<<s.Pop()<<endl;
cout<<s.GetTop()<<endl;
return 0;
}
栈的链表存储结构C++实现
最新推荐文章于 2022-02-09 14:17:14 发布