使用的開發工具CLion
CLion 2017.2.1
Build #CL-172.3544.40, built on August 2, 2017
Licensed to CLion Evaluator
Expiration date: September 15, 2017
JRE: 1.8.0_152-release-915-b6 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.12.4
1 #include <iostream> 2 using namespace std; 3 4 #define maxSize 1000 5 #define WWStr(str) #str 6 #define WWLine "-------------" 7 8 /* 9 * 目前參考內容 10 * 嚴蔚敏版數據結構 數據結構高分筆記 11 */ 12 13 //順序棧 14 typedef struct { 15 int data[maxSize]; 16 int top; 17 }SqStack; 18 19 20 //棧的初始化 21 void initSqStack(SqStack &st); 22 //輸出順序棧的內容 23 void printSqStack(SqStack st); 24 //入棧操作 25 int pushSqStack(SqStack &st,int x); 26 27 //出棧操作 28 int popSqStack(SqStack &st,int &x); 29 30 int main() { 31 32 std::cout << "Hello, World!" << std::endl; 33 34 SqStack st; 35 36 initSqStack(st); 37 38 printSqStack(st); 39 pushSqStack(st,1); 40 pushSqStack(st,2); 41 pushSqStack(st,3); 42 printSqStack(st); 43 44 int topElement; 45 46 popSqStack(st,topElement); 47 popSqStack(st,topElement); 48 cout<<"剛剛出棧的棧頂元素"<<topElement<<endl; 49 popSqStack(st,topElement); 50 printSqStack(st); 51 popSqStack(st,topElement); 52 printSqStack(st); 53 54 cout<<WWStr(str)<<WWLine<<WWStr(str)<<WWStr(-------); 55 56 57 return 0; 58 } 59 60 #pragma mark - 順序棧的初始化操作 61 void initSqStack(SqStack &st){ 62 st.top = -1; 63 } 64 65 #pragma mark - 輸出順序棧的內容 66 void printSqStack(SqStack st){ 67 cout<<"-------輸出順序棧的信息: ----地址:"<<&st<<endl; 68 for (int i = 0; i <= st.top; ++i) { 69 cout<<"順序棧st下標"<<i<<"元素"<<st.data[i]<<endl; 70 } 71 72 } 73 74 #pragma mark - 入棧操作 75 int pushSqStack(SqStack &st,int x){ 76 cout<<"-----入棧操作-----"<<"入棧元素"<<x<<endl; 77 if (st.top == maxSize){ 78 cout<<"棧為滿,不能入棧"; 79 return 0; 80 } 81 ++st.top; 82 st.data[st.top] = x; 83 return 1; 84 } 85 86 #pragma mark - 出棧操作 87 int popSqStack(SqStack &st,int &x){ 88 if (st.top == -1) { 89 cout<<"棧為空,不能出棧"<<endl; 90 return 0; 91 } 92 93 -- st.top; 94 x = st.data[st.top]; 95 cout<<"-----出棧操作----"<<"出棧元素"<<x<<endl; 96 return 1; 97 98 } 99 100 #pragma mark - 注意事項 101 void notices(){ 102 /*** 103 * 入棧 出棧要有引用參數指向棧 才能夠真的改變棧的值 104 * 出棧還要有引用參數指向出棧的元素 以記錄下來剛剛出棧的元素 105 */ 106 }
輸出的內容如下:
Hello, World!
-------輸出順序棧的信息: ----地址:0x7fff5d6039d0
-----入棧操作-----入棧元素1
-----入棧操作-----入棧元素2
-----入棧操作-----入棧元素3
-------輸出順序棧的信息: ----地址:0x7fff5d6039d0
順序棧st下標0元素1
順序棧st下標1元素2
順序棧st下標2元素3
-----出棧操作----出棧元素2
-----出棧操作----出棧元素1
剛剛出棧的棧頂元素1
-----出棧操作----出棧元素0
-------輸出順序棧的信息: ----地址:0x7fff5d6039d0
棧為空,不能出棧
-------輸出順序棧的信息: ----地址:0x7fff5d6039d0
str-------------str-------
如有問題,敬請指正