栈的链式存储结构被称为链栈(linked stack)
链栈在本质上是简化后的单链表,所有操作只集中在链表的一端,模拟栈的出栈和压栈等操作。一般选择单链表的头部来作为栈顶比较方便。
/*************************************************************************
> File Name: LinkStack.cpp
> Author: Shorey
> Mail: shoreybupt@gmail.com
> Created Time: 2015年03月23日 星期一 09时47分07秒
************************************************************************/
#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;
}