一篇文章弄懂栈的链式存储结构(c++版本)

1,链栈的定义:

栈是限定仅在表尾进行插人或删除操作的线性表。因此,对栈来说,表尾端有其特殊含义,称为栈顶,相应地,表头端称为栈底。不含元素的空表称为空栈。栈的修改是按后进先出的原则进行的,因此栈又称为后进先出的线性表,简称LIFO结构。而链栈就是使用链式结构来实现栈,链栈的空间可以是不连续分配。

结构图:

//定义结点
template<class elemtype>
class node
{
public:
	elemtype data;
	node<elemtype>* next;
};
//定义模板类
template<class elemtype>
class linkstack
{
public:
	linkstack();//构造函数,初始化空的链栈
	~linkstack();//析构函数,释放链栈中所有结点
	void push(elemtype x);//x入栈
	void pop();//栈顶元素出栈
	elemtype gettop();//取栈顶元素
	int empty();//判断链栈是否为空

private:
	node<elemtype>* top;//栈顶指针
};
template<class elemtype>
linkstack<elemtype>::linkstack()
{

}

template<class elemtype>
linkstack<elemtype>::~linkstack()
{
	while (top != NULL)
	{
		node<elemtype>* q = top;
		top = top->next;
		delete q;

	}
}

template<class elemtype>
void linkstack<elemtype>::push(elemtype x)
{
	node<elemtype>* s = new node<elemtype>;
	s->data = x;
	s->next = top;
	top = s;
}

template<class elemtype>
void linkstack<elemtype>::pop()
{
	if (top == NULL)
	{
		cout << "链栈为空" << endl;
		return;
	}
	node<elemtype>* q = top;
	top = top->next;
	delete q;
}

template<class elemtype>
elemtype linkstack<elemtype>::gettop()
{
	if (top != NULL)
	{
		return top->data;
	}
	else
	{
		cout << "linkstack为空" << endl;
	}
	
}

template<class elemtype>
int linkstack<elemtype>::empty()
{
	if (top == NULL)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x3f3f3f3f3f

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值