C++ 使用单向链表实现Stack

使用单向链表实现栈结构是一种简单且容易理解的方式

1、首先要创建一个节点类或者是结构体,这个结构体包括了该节点的下一个节点和该节点的值

template
   
   
    
    
struct node
{
	T value;  //储存的值
	node
    
    
     
     * next;

	node() :next(nullptr) {} //构造函数
	node(T t) :value(t), next(nullptr) {}
};
    
    
   
   
2、声明Stack类
template<class T>
class MyStack
{
public:
	//构造函数,包括一个起始的Node和元素个数
        MyStack() { _length = 0;_headNode = new node<T>(); };
	~MyStack();
	bool clear();
	bool isEmpty();
	int  GetLength();
	const T GetTop();

	bool Push(const T elem);

	bool Pop(T &oPopValue);
	void printStack();


private:
	int _length;
	node<T> *_headNode;

};
3、实现类
template<class T>
MyStack<T>::~MyStack()
{
	while (!isEmpty())
		Pop();
	if (_headNode)
		delete _headNode;
}

template<class T>
bool MyStack<T>::clear()
{
	while(_headNode->next)
	{
		T elemtop;
		bool isuccess = Pop(elemtop);
		if (!isucc)
		{
			return false;
		}
	}
	return true;
}

template<class T>
bool MyStack<T>::isEmpty()
{
	if (!_length)
	{
		return true;
	}
	else
		return false;
}

template<class T>
int MyStack<T>::GetLength()
{
	return _length;
}

template<class T>
const T MyStack<T>::GetTop()
{
	if (_headNode->next != nullptr)
	{
		T pValue = _headNode->next->value;
		return pValue;
	}

}

template<class T>
bool MyStack<T>::Push(const T elem)
{
	node<T>* pNode = new node<T>(elem);
	//采用头插法,即pNode代替栈顶的,所以pNode的下一个应为head的下一个;
	pNode->next = _headNode->next;
	_headNode->next = pNode;
	_length++;
	return true;
}

template<class T>
bool MyStack<T>::Pop(T &oPopValue)
{
	if (_headNode->next!=nullptr)
	{
		node<T>* TopNode = _headNode->next;
		_headNode->next = TopNode->next();
		oPopValue = TopNode->value;
		_length--;
		delete  TopNode;
		return true;
	}
	else
		return false
}

template<class T>
void MyStack<T>::printStack()
{
	if (_headNode->next != nullptr)
	{
		node<T> *pNode = _headNode->next;
		cout << pNode->value << endl;
		while (pNode->next)
		{
			cout << pNode->next->value << endl;
			pNode = pNode->next;
		}


	}
}
4、上述实现了stack的基本功能,其他功能可以继续拓展,然后测试
int main()
{
	MyStack<int> *opStack = new MyStack<int>();
	int a;
	while (cin>>a)
	{
		opStack->Push(a);
	}


	opStack->printStack();
	system("pause");
}

5、测试结果
输入:1 2 3 4 5
输出:5 4 3 2 1

参考文章
http://blog.csdn.net/u013445530/article/details/43381833
http://blog.csdn.net/yzl_rex/article/details/6692500
http://blog.csdn.net/qq_15718789/article/details/52743278



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值