欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构与算法_链式栈

程序员文章站 2022-06-05 15:05:07
...

LinkStack.h

#pragma once
#include <iostream>
using namespace std;
template<class T>	class LinkStack;	//前置声明 

template<class T>
class ListNode
{
	friend class LinkStack<T>;
private:
	T data;
	ListNode<T>* next;
	//私有构造函数
	ListNode(const T& theData, ListNode* n=0):data(theData), next(n)
	{} 
} ;

template<class T>
class LinkStack
{
public:
	LinkStack():top(0){}
	~LinkStack(){ MakeEmpty();}
	bool IsEmpty() const;
	T& Top() const;
	void Push(const T& e);
	void Pop();
	void MakeEmpty();
private:
	ListNode<T> *top;
} ;

template<class T>
void LinkStack<T>::MakeEmpty()
{
	while(!IsEmpty())
	{
		Pop();
	}
}
template<class T>
bool LinkStack<T>::IsEmpty() const
{
	return (top == 0);
}

template<class T>
void LinkStack<T>::Push(const T& e)
{
	//新创建一个节点赋值给top,在构造时让指针指向原来的top 
	top = new ListNode<T>(e, top);
} 
template<class T>
T& LinkStack<T>::Top() const
{
	if(this->IsEmpty())
		throw "Stack is empty!";
	else
		return top->data;
}
template<class T>
void LinkStack<T>::Pop()
{
	if(this->IsEmpty())
		throw "Stack is empty, Cannot delete!";
	ListNode<T> *DeleteNode = top;
	top = top->next;
	delete DeleteNode;
		
}

main.h

#include <iostream>
#include "LinkStack.h"
using namespace std;
 


int main() 
{
	LinkStack<int> List;
	List.Push(10);
	cout << List.Top() << endl; 
 	List.Push(20);
 	cout << List.Top() << endl; 
	List.Push(30);
	List.Pop();
	cout << List.Top() << endl; 
	List.MakeEmpty();
	cout << List.Top() << endl; 
	cout << "hello " << endl; 
	return 0;
}

数据结构与算法_链式栈

相关标签: 数据结构与算法