链栈的实现
一、实验目的
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无法判断就会出错,多练习,争取少犯错误。