实验三之链栈的实现

来源:互联网 发布:淘宝回购率在哪里看 编辑:程序博客网 时间:2024/04/20 01:56
#include<iostream>using namespace std;template<class T>struct Node{T data;Node<T> *next;};template<class T>class Linkstack{public:Linkstack(){top=NULL;}~Linkstack();void Push(T x);T Pop();T Gettop(){return top->data;}int Empty(){return top==NULL;}void Print();private:Node<T> *top;};template<class T>Linkstack<T>::~Linkstack(){Node<T> *ptr=NULL;while(top!=NULL){ptr=top->next;delete top;top=ptr;}}template<class T>void Linkstack<T>::Push(T x){Node<T> *s;s=new Node<T>;s->data=x;s->next=top;top=s;}template<class T>T Linkstack<T>::Pop(){Node<T> *p;if(top==NULL) throw"栈为空,出栈失败!";int x=top->data;p=top;top=top->next;delete p;return x;}template<class T>void Linkstack<T>::Print(){Node<T> *p;    p=top->next;    while(p!=NULL)    {        cout<<p->data<<" ";        p=p->next;    }    cout<<endl;}int main(){cout<<"创建一个链栈:"<<endl;Linkstack<int> s;if(s.Empty())cout<<"栈为空"<<endl;elsecout<<"栈中已有元素,且栈未满"<<endl;cout<<"向栈中分别插入1,2,3,4,5,6,7,8,9:"<<endl;s.Push(1);s.Push(2);s.Push(3);s.Push(4);s.Push(5);s.Push(6);s.Push(7);s.Push(8);s.Push(9);cout<<"完成入栈操作!此时栈中元素有:"<<endl;s.Print();cout<<"取出栈顶元素为:"<<s.Gettop()<<endl;s.Pop();cout<<"执行完一次出栈操作后的结果为:"<<endl;s.Print();return 0;}

一、实验目的

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


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

二、实验内容

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


2、建立一个链栈,实现栈的压栈和出栈操作。

三、运行结果截图


四、实验心得

通过这几次的实验开始对线性表、栈之间的练习和区别有了一些了解,也开始有意识地去分析两者的共同之处和不同之处,在编写代码的时候,常常会出现与之前操作的错误,然后渐渐可以尝试着自己去修改,而不是一开始那样一出错就去翻书或者上网查询,这也是自己意识到自己在编程方面独立思考的意识有所提升的表现。
但是自己的程序依然不够完善,自己的编程能力也还很弱,但是无论如何,对编程算是有了更大的耐心和兴趣。