实验二链栈

#include<iostream>
using namespace std;
struct Node
{
    int data;
	struct Node*next;
};
class LinkStack
{
	public:
		LinkStack(){top=NULL;}
		~LinkStack();
		void Push(int x);
		int Pop();
		int GetTop();
		int Empty();
	private:
		Node*top;
};
void LinkStack::Push(int x)
{
	Node*s;
	s=new Node;
	s->next=top;
	top=s;
}
int LinkStack::Pop()
{
	int x;
	Node*p;
    if(top==NULL)throw"下溢";
	x=top->data;
	p=top;
	top=top->next;
	delete p;
	return x;
}
int LinkStack::GetTop()
{
		return top->data;
}
int LinkStack::Empty()
{
	if(top==NULL)return 1;
	else return 0;
}
int main()
{
	LinkStack S;
    if(S.Empty())
        cout<<"栈为空"<<endl;
	else
		cout<<"栈非空"<<endl;
	cout<<"对66和99执行入栈操作"<<endl;
	S.Push(66);
	S.Push(99);
	cout<<"栈顶元素为:"<<endl;
	cout<<S.GetTop()<<endl;
	cout<<"执行一次出栈操作"<<endl;
	S.Pop();
	cout<<"栈顶元素为:"<<endl;
	cout<<S.GetTop()<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41937706/article/details/80101764