链栈实现

来源:互联网 发布:大数据架构师 知乎 编辑:程序博客网 时间:2024/06/08 11:14

一、实验目的

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

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

二、实验内容

1、自己确定结点的具体数据类型和问题规模:

分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。

三、源代码

#include<iostream>using namespace std;template<typename T>struct Node{T data;Node<T> *next;};template<typename T>class Linklist{private:Node<T> *top;//top指针int length;public:Linklist(){top=NULL;length=0;}//构造函数~Linklist(){}//析构函数int Length();//栈的长度void Push(T x);//入栈T Pop();//出栈T GetTop(){if(top!=NULL) return top->data;}//取栈顶元素void Empty();//判断栈是否为空};template<class T>void Linklist<T>::Push(T x){Node<T> *s;s=new Node<T>;s->data=x;s->next=top;top=s;length++;}template<class T>int Linklist<T>::Length(){return length;}template<class T>T Linklist<T>::Pop(){if(top==NULL) throw"下溢";T x=top->data;Node<T> *p;p=top;top=top->next;delete p;length--;return x;}template<class T>void Linklist<T>::Empty(){if(top==NULL)cout<<"1";elsecout<<"0";}void main(){Linklist<int> b;cout<<"判断栈是否为空,若空则1,否为0:";b.Empty();cout<<endl;b.Push(1);b.Push(2);b.Push(3);b.Push(4);b.Push(5);cout<<"元素1,2,3,4,5入栈后栈的长度为:"<<b.Length()<<endl;cout<<"取栈顶元素:"<<b.GetTop()<<endl;cout<<endl;cout<<"栈顶出栈"<<endl;b.Pop();cout<<"取栈顶元素:"<<b.GetTop()<<endl;cout<<"栈的长度为:"<<b.Length()<<endl;}
四、运行结果