/*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 關注
- 159 瀏覽
添加回答
舉報
0/150
提交
取消