实验之链栈
实验目的:
熟练应用栈的链式存储结构——链栈,并了解其运作原理,编写代码实行。
实验要求:
应用链栈完成学生信息的入栈,出栈,编写代码并完成操作。
实验代码:
头文件:
#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。