1. 棧的定義node
示意圖:數據結構
2. 棧的基本運算ide
棧的幾種狀態(最大長度MaxSize爲4):棧空、壓棧、棧滿、出棧spa
3. 棧的存儲結構3d
棧有兩種表示方法:順序存儲和鏈式存儲指針
3.1 順序棧code
採用順序存儲結構的棧簡稱爲順序棧。是利用一組地址連續的存儲單元依次存放自棧底到棧頂的數據元素,同時附設整型變量top指示棧頂元素在順序棧中的位置。blog
// 順序棧數據類型的C語言描述以下: #define MaxSize 100 typedef int DataType; typedef struct { DataType data[MaxSize]; int top; }Stack; // top:棧頂指針。取值範圍爲0~MaxSize-1。 // top==-1表示棧空,top==MaxSize-1表示棧滿。
// 初始化棧InitStack(S) int InitStack(Stack *S) { S->top=-1; return 1; } // 壓棧Push(S,x) int Push(Stack *S,DataType x) { if(S->top==MaxSize-1) { printf("\n Stack is full!"); return 0; } S->top++; S->data[S->top]=x; return 1; } // 判棧空EmptyStack(S) int EmptyStack(Stack *S) { return (S->top==-1?1:0); } // 出棧Pop(S,x) int Pop(Stack *S,DataType *x) { if(EmptyStack(S)) { printf("\n Stack is free!"); return 0; } *x=S->data[S->top];//記住要刪除的元素值 S->top--; return 1; } // 取棧頂元素GetTopStack(S) DataType GetTop(STACK *S) { DataType x; if(EmptyStack(S)) { printf("\n Stack is free!"); exit(1); } x=S->data[S->top]; return x; }
3.1 鏈棧:棧的鏈式存儲結構it
鏈棧結構示意圖:event
top棧頂指針,唯一的肯定一個鏈棧。 鏈棧一般帶有一個表頭結點,因此top->next才指示棧頂元素。
// 鏈棧的C語言描述以下:
typedef struct node { ElemType data; struct node *next; }Stack;
Stack * InitStack() { Stack *top; top=(Stack *)malloc(sizeof(Stack)); top->next=NULL; return top; } //進棧 int Push(Stack *top,Pos x) { Stack *s; s=(Stack *)malloc(sizeof(Stack)); if(!s) //當s==NULL return 0 return 0; s->data=x; s->next=top->next; //新申請空間的指針域保存上一個結點的地址 top->next=s; //頭指針域保存新結點地址 return 1; } //判斷棧空 int EmptyStack(Stack *top) { if(top->next==NULL) return 1; else return 0; } //出棧 int Pop(Stack *top,Pos *e) { Stack *s; if(EmptyStack(top)) return 0; s=top->next; //取第一個結點的地址 *e=s->data; //返第一結點數據 top->next=s->next; //頭結點指針域存第二結點地址 free(s); return 1; } //取棧頂元素 int GetTopStack(Stack *top,Pos *e) { Stack *s; if(EmptyStack(top)) return 0; s=top->next; *e=s->data; return 1; }