堆棧(Stack):具備必定操做約束的線性表數組
類型名稱:堆棧(stack)ide
數據對象集:一個有0個或多個元素的又窮線性表。spa
操做集:長度爲MaxSize的堆棧S∈Stack,堆棧元素item∈ElementType3d
一、Stack CreateStack(int MaxSize):生成空堆棧,其最大長度爲MaxSzie;指針
二、int IsFull(Stack S, int MaxSize):判斷堆棧S是否已滿code
三、void Push(Stack S, ElementType item):將元素item壓入堆棧對象
四、int IsEmpty(Stack S):判斷堆棧S是否爲空blog
五、ElementType Pop(Stack S):刪除並返回棧頂元素it
棧的順序存儲實現event
棧的順序存儲結構一般由一個一維數組和一個記錄棧頂元素位置的變量組成。
#define MAXSIZE 100 typedef struct SNode *Stack; struct SNode{ ElementType Data[MAXSIZE]; int Top; }
入棧
void Push(Stack PtrS, ElementType item) { if(PtrS->Top == MAXSIZE - 1) { printf("Stack full"); return; } else { PtrS->Data[++(PtrS->Top)] = item; return; } }
出棧
ElementType Pop(Stack PtrS) { if(PtrS->Top == -1) { printf("Stack Empty"); return ERROR; } else return(PtrS->Data[(PtrS->Top)--]); }
例子:請用要給數組實現兩個堆棧,要求最大地利用數組空間,使數組只要有空間入棧操做就能夠成功。
1 #define MAXSIZE 100 2 struct DStack{ 3 ElementType Data[MAXSIZE]; 4 int Top1; 5 int Top2; 6 }S; 7 S.Top1 = -1; 8 S.Top2 = MAXSIZE; 9 10 void Push(struct DStack *PtrS, ElementType item, int Tag) 11 { 12 if(PtrS->Top2 - PtrS->Top1 == 1) { 13 printf("stack full"); 14 return; 15 } 16 if(Tag == 1) 17 PtrS->Data[++(PtrS->Top1)] = item; 18 else 19 PtrS->Data[--(PtrS->Top2)] = item; 20 } 21 22 ElementType Pop(stuct DStack *PtrS, int Tag) 23 { 24 if(Tag == 1) { 25 if(PtrS->Top == -1) { 26 ptintf("Stack1 Empty"); 27 return; 28 } else { 29 return(PtrS->Data[(PtrS->Top1)--]) 30 } 31 } else { 32 if(PtrS->Top2 == MAXSIZE) { 33 printf("Stack2 Empty"); 34 return; 35 } else { 36 return PtrS->Data[(PtrS->Top2)--]; 37 } 38 } 39 }
站的鏈式存儲結構實際上就是一個單鏈表,叫作鏈棧。插入和刪除操做智能在鏈棧的棧頂進行。棧頂指針Top應該在鏈表的哪一頭?
typedef struct SNode *Stack; struct SNode{ ElementType Data; struct SNode *Next; };
堆棧初始化
Stack CreateStack() { Stack = s; S = (Stack)malloc(sizeof(struct SNode)); S->Next = NULL; return S; }
判斷堆棧S是否爲空
int IsEmpty(Stack S) { return (S->Next == NULL); }
push操做
void Push(ElementType item, Stack S) { struct SNode *TmpCell; TmpCell = (SNode)malloc(sizeof(struct SNode)); TmpCell->Data = item; TmpCell->Next = S->Next; S->Next = TmpCell; }
pop操做
ElementType Pop(Stack S) { struct SNode *FirstCell; ElementType TopElem; if(IsEmpty(S)) { printf("Stack Empty"); return NULL; } else { FirstCell = S->Next; S->Next = FirstCell->Next; TopElem = FirstCell->Data; free(FirstCell); return TopElem; } }