链栈

链栈的实现

一、实验目的

1.熟练栈的链式存储结构和实现。

二、实验步骤

#include<iostream>
#include<iomanip>   //使用了setw()
#include<stdlib.h>
using namespace std;

template<class T>
struct Node
{
	T data;
	Node<T>*next;
};

template<class T>
class SeqStack
{
public:
	SeqStack() { top = new Node<T>; top = NULL; }   /*初始化一个空栈*/
	~SeqStack();
	void Push(T x);   /*将x入栈*/
	T GetTop() {  /*弹出栈顶元素*/
		if (top != NULL)
			return top->data;
	}
	T Pop();   /*出栈*/
	int Empty() {   /*判断栈是否为空*/
		if (top == NULL)
		{
			return 1;
		}
		else {
			return 0;
		}
	}
private:
	Node<T>*top;
};
template<class T>
SeqStack<T>::~SeqStack()
{
	Node<T>*t;
	while (top != NULL)
	{
		t = top;
		top = top->next;
		delete t;
	}
}

template<class T>
void SeqStack<T>::Push(T x)
{
	Node<T>*s;
	s = new Node<T>;
	s->data = x;
	s->next = top;
	top = s;
}

template<class T>
T SeqStack<T>::Pop()
{
	if (top == NULL) throw"下溢";
	else {
		Node<T>*p;
		p = new Node<T>;
		p = top;
		T x = p->data;
		top = top->next;
		delete p;
		return x;
	}

}
void main()                   //主函数
{
	SeqStack<int>S;            //创建模板类的实例
	if (S.Empty())
		cout << "栈为空" << endl;
	else
		cout << "栈非空" << endl;
	cout << "对15和10执行入栈操作" << endl;
	S.Push(15);
	S.Push(10);
	cout << "栈顶元素为:" << endl;   //取栈顶元素
	cout << S.GetTop() << endl;
	cout << "执行一次出栈操作" << endl;
	S.Pop();                       //执行出栈元素
	cout << "栈顶元素为:" << endl;
	cout << S.GetTop() << endl;
	system("pause");
}

三、实验结果

四、实验心得

判断是否为空的函数返回值在另外一个函数调用的时候,要分别清楚类型,比如if判断的条件要准确,要是判断的是调用Empty(),而之前的Empty函数定义的为:是空cout<<"空"<<endl;不是空cout<<"非空"<<,这里的if无法判断就会出错,多练习,争取少犯错误。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值