/*2.a 实现栈模板类要求:1)用链表形式来存储栈数据2)实现栈的常用函数*/#include <iostream>using namespace std;template <class T>class Mystack{ struct Node { T data; Node *next; }; Node *head;public:Mystack(){head=NULL;}~Mystack(){while(head!=NULL){Node*p=head;head=p->next;delete p;}}void input(){cout<<"开始输入数据"<<endl;T x;cin>>x;while(x!=-1){Node *p=new Node ;p->data=x;p->next=head;head=p;cin>>x;}}T push(T n){T num=n;Node *p=new Node;p->data=num;p->next=NULL;if(head==NULL){head=p;return num;}else{p->next=head;head=p;return num;}}T pop(){if(head==NULL)return -1;else{T x=head->data;Node *p=head;head=head->next;delete p;return x;}}void display(){Node *p=head;for(;p!=NULL;p=p->next)cout<<p->data<<" ";cout<<endl;}void gettop(){if(head==NULL)cout<<"the stack is empty!"<<endl;elsecout<<"the top number is "<<head->data<<endl;}bool empty(){if(head==NULL)return true;elsereturn false;}};void main(){Mystack<int> h;cout<<"开始输入数据(为int型)"<<endl;h.input();h.gettop();int x;cout<<"输入进栈的数据(为int型)"<<endl;cin>>x;if(h.push(x)==x)cout<<"进栈成功!"<<endl;cout<<"进栈之后的数据输出:"<<endl;h.display();if(!(h.pop()==-1)){cout<<"出栈成功!"<<endl;cout<<"出栈之后的数据输出:"<<endl;h.display();}elsecout<<"栈内没有数据"<<endl;cout<<endl;cout<<"**************************************"<<endl;Mystack<double> t;cout<<"开始输入数据(为double型)"<<endl;t.input();t.gettop();double y;cout<<"输入进栈的数据(为double型)"<<endl;cin>>y;if(t.push(y)==y)cout<<"进栈成功!"<<endl;cout<<"进栈之后的数据输出:"<<endl;t.display();if(!(t.pop()==-1)){cout<<"出栈成功!"<<endl;cout<<"出栈之后的数据输出:"<<endl;t.display();}elsecout<<"栈内没有数据"<<endl;}
- 2 回答
- 0 关注
- 143 浏览
添加回答
举报
0/150
提交
取消