数据结构-链栈的c++实现

#pragma once
#ifndef My_Head_H
	#define My_Head_H
	#include "G://code/c++/myhead.h"
#endif // !My_Head_H
template <typename ElemType>
class LinkStack
{
public:
	class Stack_Node
	{
	public:
		ElemType data;
		Stack_Node *next;
	};
	typedef Stack_Node* Nodepointer;

	//把栈置空
	void clear();

	//求栈中结点个数
	int Get_Length();

	//弹出栈顶结点
	Status Pop(ElemType& e);

	//压入数据为e的结点
	void Push(ElemType e);

	//以随机数填充i个结点
	void Random_Fill_Stack(int i);

	//打印所有节点
	void Display_Stack();

	//链栈构造函数
	LinkStack();

	//链栈析构函数
	virtual ~LinkStack();

protected:
	Nodepointer top;
};

template<typename ElemType>
void LinkStack<ElemType>::clear()
{
	Nodepointer s;
	while (top)
	{
		s = top;
		top = top->next;
		delete s;
	}
	top = NULL;
}

template<typename ElemType>
int LinkStack<ElemType>::Get_Length()
{
	Nodepointer s;
	int count = 0;
	s = top;
	while (s)
	{
		count++;
		s = s->next;
	}
	return count;
}

template<typename ElemType>
Status LinkStack<ElemType>::Pop(ElemType& e)
{
	Nodepointer s = top;
	if (!top) return ERROR;
	e = top->data;
	top = top->next;
	delete s;
	return OK;
}

template<typename ElemType>
void LinkStack<ElemType>::Push(ElemType e)
{
	Nodepointer s;
	s = new Stack_Node;
	s->data = e;
	s->next = top;
	top = s;
}

template<typename ElemType>
void LinkStack<ElemType>::Random_Fill_Stack(int i)
{
	for (int count = 0; count < i; count++)
	{
		Push(random(100));
	}
}

template<typename ElemType>
void LinkStack<ElemType>::Display_Stack()
{
	Nodepointer s = top;
	cout << "Here is all Stack Data:" << endl;
	while (s)
	{
		cout << "->" << s->data;
		s = s->next;
	}
	cout << endl;
	return;
}

template<typename ElemType>
LinkStack<ElemType>::LinkStack()
{
	top = NULL;
}

template<typename ElemType>
LinkStack<ElemType>::~LinkStack()
{
	clear();
}


myhead.h在另一篇博文里:https://blog.csdn.net/cwdben/article/details/105906918

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值