堆疊的儲存結構及其基礎操作
阿新 • • 發佈:2020-07-01
今天覆習了棧的內容,接下來更新相關應用
/*棧的順序儲存實現*/
/* 棧的順序儲存結構通常由一維陣列和一個記錄棧頂元素的位置的變數組成*/
一、順序棧
1.結構體
typedef struct SNode *Stack; struct SNode { ElementType Data[MaxSize]; int Top; };
2.入棧
void Push(Stack PtrS,ElementType item) { if(PtrS->Top == MsxSize-1) { printf("堆疊滿");return; } else{ PtrS->Data[++(PtrS->Top)] == item; return; } }
3.出棧
ElementType Pop(Stack PtrS) { if(PtrS->Top == -1) { printf("堆疊空"); return ERROR; /*ERROR 是ElementType的特殊值,標誌錯誤 */ } else { return PtrS->Data[PtrS->Top]; PtrS->Top--; } }
二、雙棧
1.結構體
typedef struct { ElementType Data[MaxSize]; int top1; int top2; }S; S->top1 = -1; S->top2 = MaxSize;
2.入棧
void Push(S *PtrS,ElementType item,int Tag) //Tag是區分兩個棧的標誌取值為1和2 { if(PtrS->top2 - PtrS->top1 == 1) { printf("堆疊滿"); return; } if(Tag == 1) //對第一個棧操作 PtrS->Data[++(PtrS->top1)] = item; else PtrS->Data[--(PtrS->top2)] = item; }
3.出棧
ElementType Pop(S *PtrS,int Tag) { if(Tag == 1 ) { if(PtrS->Top1 == -1) { printf("棧1空"); return NULL; } else return PtrS->Data[(PtrS->top1)--]; } else { if(PtrS->Top2 == MaxSize) { printf("棧2空"); return NULL; } else return PtrS->Data[(PtrS->top2)++ ]; } }
三、鏈式儲存
//棧的鏈式儲存結構實際上就是一個單鏈表,叫做鏈棧。插入和刪除智慧在棧的棧頂進行。
1.結構體
typedef struct SNode *Stack; struct SNode { ElementType Data; struct SNode *Next; };
2.構造頭節點
Stack CreateStack() { //構建一個堆疊的頭節點,返回指標 Stack S; S = (Stack)malloc(sizeof(struct SNode)); S->Next = NULL; return S; }
3.判斷棧是否為空
int IsEmpty(Stack S) /*判斷是否為空 若為空 返回 1 否則返回1 */ { return (S->Next == NULL); }
4.入棧
/*入棧*/ void Push(ElementType item,Stack S) /*將item壓入棧*/ { Stack TmpCell; //申請一個空節點 TmpCell = (Stack)malloc(sizeof(struct SNode)); TmpCell->Data = item; TmpCell->Next = S->Next; S->Next = TmpCeLL; }
5.出棧
ElementType Pop(Stack S) { //刪除並返回棧頂S的元素 Stack FirstCell; ElemType TopElem; if(IsEmpty(S)) { printf("堆疊空");return NULL; } else { FirstCell = S->Next; S->Next = FirstCell->Next; TopElem = FirstCell->Data; free(FirstCell); return TopElem; } }
以上就是小白的總結,程式碼沒有除錯,如有問題請在下方留言喲~