1. 程式人生 > >6 線性表-棧-順序存儲

6 線性表-棧-順序存儲

pre bsp log truct == names end emp lib

自己簡直是強迫癥晚期,上次因為對訪問結構體成員該用什麽方法困惑了很久,導致沒把順序存儲的搗鼓出來(明明比鏈式的要好寫)

今天花了個20分鐘調好了

因為今天比較晚,趕時間就沒給類型起別名用ElemType寫,直接用了int類型。需要的話可以自行更改。

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<iostream>
 4 using namespace std;
 5 #define maxsize 50
 6 /*順序棧的定義*/
 7 typedef struct Snode{
 8 int data[maxsize];
9 int top; 10 }SqStack; 11 /*棧的初始化:設置S.top為1,站頂元素是S.data[top]*/ 12 void InitStack(SqStack *S) 13 { 14 (*S).top=-1; 15 } 16 /*判斷棧是否為空:top==-1*/ 17 int StackEmpty(SqStack *S) 18 { 19 if(S->top==-1) return 1; 20 else return 0; 21 } 22 /*入棧*/ 23 int Push(SqStack *S,int x) 24 { 25 if(S->top==maxsize-1
)//棧滿了 26 return -1; 27 S->data[++S->top]=x; 28 /*這裏等價於 29 S->top++; 30 S->data[S->top]=x; 31 先指針加一再入棧 32 */ 33 // cout<<"push the data x:"<<x<<endl; 34 return 1; 35 } 36 /*讀取棧頂元素*/ 37 int GetTop(SqStack *S,int &x) 38 { 39 if
(S->top==-1)//棧空 40 return -1; 41 x=S->data[S->top]; 42 return 1; 43 } 44 /*出棧*/ 45 int Pop(SqStack *S,int x) 46 { 47 if(S->top==-1) 48 return -1;//棧空,啥也吐不出來 49 x=S->data[S->top--]; 50 51 /*等價於 52 x=S->data[S->top]; 53 S->top--; 54 */ 55 return 1; 56 } 57 int main() 58 { 59 SqStack *S=(SqStack *)malloc(sizeof(SqStack));//一定要先生成一個指針 60 InitStack(S); 61 cout<<(*S).top<<endl; 62 int a1=StackEmpty(S); 63 cout<<a1<<endl; 64 cout<<"Test the function ‘Push‘,input a data:"; 65 cin>>a1; 66 Push(S,a1); 67 int w; 68 cout<<"Before GetTop,w is"<<w<<endl; 69 70 GetTop(S,w); 71 cout<<"After GetTop,w is "; 72 cout<<w<<endl; 73 int q=100; 74 Push(S,q); 75 GetTop(S,w); 76 cout<<w<<endl; 77 cout<<"-------------------------------------"<<endl; 78 cout<<"Test the function ‘Pop‘:"; 79 Pop(S,w); 80 cout<<w<<endl; 81 cout<<"After Pop a data,the top of stack is:"; 82 GetTop(S,w); 83 cout<<w<<endl; 84 return 0; 85 }

6 線性表-棧-順序存儲