栈的链式存储结构C++实现

栈的链式存储结构被称为链栈(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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值