資料結構實驗二鏈棧
#include<stdlib.h>
struct Node
{
int data;
Node *next;//*結構體指標*//
};
class Stack
{private:static int count;
Node *top;
public:
Stack(){top=NULL;}
void Insert(int data){
Node *s; s=(Node*)malloc(sizeof(Node));s->data=data;s->next=top;top=s;count++;}
int GetTop(){if(top==NULL)return 0;else return top->data;}
int Pop(){if(top==NULL)return 0;
else{Node *p;int x;x=top->data;p=top;top=top->next;delete p;return x;}}
void Show(){for(int i=0;i<=count-1;i++){
cout<<top->data<<" ";top=top->next;};}
};
int Stack::count=0;
int main()
{Stack S;void menu();
int i;
do{menu();cout<<"Please enter your choice:";cin>>i;
switch(i)
{
case 1:int a;cout<<"Please enter a number:";cin>>a;S.Insert(a);break;
case 2:int b;b=S.GetTop();if(b==0)cout<<"棧空!"<<endl;else cout<<"棧頂:"<<S.GetTop()<<endl;break;
case 4:break;
case 3:int c;c=S.Pop();if(c==0)cout<<"棧空!"<<endl;else cout<<"彈出後的棧頂為:"<<S.Pop()<<endl;break;
case 5:S.Show();cout<<endl;break;
default:cout<<"enetr error!"<<endl;break;
}}while(i!=4);
return 0;
}void menu(){
cout<<"請選擇下列功能:"<<endl;
cout<<"1--入棧;"<<endl;
cout<<"2--取棧頂;"<<endl;
cout<<"3--彈棧"<<endl;
cout<<"4--退出;"<<endl;
cout<<"5--顯示後刪除所有資料."<<endl;}