棧(C++語言 C風格實現)
阿新 • • 發佈:2020-12-15
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 using namespace std; 5 #define MAX_SIZE 100 6 typedef struct Stack{ 7 int data[MAX_SIZE]; 8 int top; 9 }stack; 10 //初始化棧 11 void createStack(stack &s){ 12 s.top = -1; 13 } 14 //入棧 15 void push(stack &s,intnum){ 16 if(s.top == MAX_SIZE-1){ 17 cout<<"入棧失敗,棧已滿"<<endl; 18 return; 19 } 20 s.data[++s.top] = num; 21 } 22 int pop(stack &s){ 23 return s.data[s.top--]; 24 } 25 26 void display(stack s){ 27 cout<<"遍歷棧:"<<endl; 28 if(s.top == -1){ 29 cout<<"棧為空"<<endl; 30 } 31 32 for(int i = 0;i<=s.top;i++){ 33 cout<<s.data[i]<<" "; 34 } 35 cout<<endl; 36 } 37 bool isEmpty(stack s){ 38 if(s.top == -1) return true; 39 return false; 40 } 41 int main(){ 42 stack s; 43 createStack(s);44 for(int i = 0;i<10;i++){ 45 push(s,10-i); 46 } 47 display(s); 48 while(isEmpty(s) == false){ 49 cout<<"出棧,且出棧元素為:"<<pop(s)<<endl; 50 } 51 return 0; 52 }