实验之链栈

实验目的:

熟练应用栈的链式存储结构——链栈,并了解其运作原理,编写代码实行。


实验要求:

应用链栈完成学生信息的入栈,出栈,编写代码并完成操作。


实验代码:

头文件:

#include <iostream>
template<class T>
class Node
{
public:
 T data;
 Node  *next;
 
};
template<class T>
class Linkstack{
public:
 Linkstack(){top=NULL;}
 void push();
 T pop();
 T Gettop(){if (top!=NULL) return top->data;}
 int empty(){if (top==NULL) return 1; else return 0;}
private:
    Node <T> *top;
};

源文件:

#include "tou.h"
#include<iostream>
using namespace std;
template <class T>
void Linkstack<T>::push(){
 T x; cin>>x;
 Node<T> *s=new Node<T>;
  s->data=x;
 s->next=top;
 top=s;
}

template <class T>
T Linkstack<T>::pop(){
 T x; Node <T>*p;
 if(top==NULL) throw"over";
 x=top->data; p=top;
 top=top->next;
 delete p;
 return x;
}
 
void main(){
 Linkstack<int> x;
 int i; int n;
 cout<<"please the number"<<endl;
 cin>>n;
 for(i=1;i<=n;i++){
  x.push();
 }
 cout<<x.Gettop()<<endl;
 cout<<x.empty()<<endl;
 for(i=1;i<=n;i++){
  cout<<x.pop()<<endl;
 }
 system("pause");
}


实验结果:


实验总结:

应用链式存储结构,需要创造结点,链式存储结构特点是:灵活应用零散空间存储信息,可并不特别节省空间,且链栈操作也受限,除析构函数外,链栈的算法时间复杂度均为1。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值