实验三链栈

一、实验目的

1、   熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。

2、      学会使用栈和队列解决实际问题。

#include<iostream>
using namespace std;
template<typename T>
struct Node
{
	T data;
	Node<T>*next;
};
template<typename T>
class LinkStack{
	public:
		LinkStack(T array[],int n)
		{
			top=NULL;
			Node<T>*node=NULL;
			for(int i=0;i<n;i++)
			{
				node=new Node<T>;
				node->data=array[i];
				node->next=top;
				top=node;
			}
		}
		~LinkStack()
		{
			Node<T>*deleteNode=NULL;
			deleteNode=top;
			top=top->next;
			delete deleteNode;
		}
		void Push(T x);
		void Print();
		T Pop();
		T GetTop(){if(top!=NULL)return top->data;}
		int Empty(){top==NULL?return 1:return 0;}
	private:
		Node<T>*top;
};
template<typename T>
void LinkStack<T>::Push(T x)
{
	Node<T>*s;
	s=new Node<T>;
	s->data=x;
	s->next=top;
	top=x;
}
template<typename T>
T LinkStack<T>::Pop()
{
	T x;
	Node<T>*p;
	if(top==NULL)throw"下溢";
	x=top->data;
	p=top;
	top=top->next;
	delete p;
	return x;
}
template<class T>
void LinkStack<T>::Print()
{
	Node<T>*node=top;
	while(node->next!=NULL)
	{
		cout<<node->data<<"";
		node=node->next;
	}
	cout<<node->data<<endl;
}
void main()
{
	int arr[]={1,2,3,4,5};
	cout<<"1,2,3,4,5,入栈"<<endl;
	LinkStack<int>a(arr,5);
	cout<<"遍历"<<""<<endl;
	a.Print();
	cout<<"出栈一个元素"<<a.Pop()<<endl;
	a.Print();
	cout<<"栈顶元素为:"<<a.GetTop()<<endl;
}

猜你喜欢

转载自blog.csdn.net/Sing___546/article/details/78280774