棧 線性數據結構的一種 能夠理解爲操做受限的線性表
數據結構
棧的特色 先入後出 (能夠想象一下裝羽毛球的球筒,先放進去的在最底下)spa
棧的表尾端稱爲棧頂,表頭稱爲棧底,插入和刪除都只能在棧頂操做,插入操做稱爲入棧,彈出操做稱爲出棧。
指針
下面是棧的順序存儲結構的C實現代碼code
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define INIT_SIZE 20 #define INCREMENT_SIZE 5 typedef int SElemType; typedef int Status; /* * 存儲結構 */typedef struct{ SElemType *base; //棧尾指針 SElemType *top; //棧頂指針 int size; //棧的大小}SqStack;/* * 初始化棧 */ Status InitStack(SqStack *S){ S->base = (SElemType*) malloc(INIT_SIZE * sizeof(SElemType)); if (!S->base) { exit(OVERFLOW); } S->top = S->base; S->size = INIT_SIZE; return OK; } /* * 銷燬棧 */Status DestroyStack(SqStack *S){ free(S->base); S->base = NULL; S->top = NULL; S->size = 0; return OK; } /* * 清空棧 */Status ClearStack(SqStack *S){ S->top = S->base; return OK; }/* * 判斷棧是否爲空 */ Status IsEmpty(SqStack S){ if (S.top == S.base) { return TRUE; } else return FALSE; } /* * 獲取棧的長度 */ int GetLength(SqStack S){ return (S.top - S.base) / sizeof(SElemType); } /* * 獲取棧頂元素 */ Status GetTop(SqStack S, SElemType *e){ if (S.top > S.base) { *e = *(S.top - sizeof(SElemType)); return OK; } else { return ERROR; } } /* * 壓棧 */ Status Push(SqStack *S, SElemType e){ if ((S->top - S->base) / sizeof(SElemType) >= S->size) { S->base = (SElemType*) realloc(S->base, (S->size + INCREMENT_SIZE) * sizeof(SElemType)); if (!S->base) { exit(OVERFLOW); } S->top = S->base + S->size * sizeof(SElemType); S->size += INCREMENT_SIZE; } *S->top = e; S->top += sizeof(SElemType); return OK; } /* * 退棧 */ Status Pop(SqStack *S, SElemType *e){ if (S->top == S->base) { return ERROR; } S->top -= sizeof(SElemType); *e = *S->top; return OK; } /* * 訪問元素 */ void visit(SElemType e){ printf("%d ", e); } /* * 遍歷棧 */ Status TraverseStack(SqStack S, void (*visit)(SElemType)){ while (S.top > S.base) { visit(*S.base); S.base += sizeof(SElemType); } return OK; } int main(){ SqStack S; if (InitStack(&S)) { SElemType e; int i; printf("init_success\n"); if (IsEmpty(S)) { printf("Stack is empty\n"); } for (i = 0; i < 10; i++) { Push(&S, i); } GetTop(S, &e); printf("The first element is %d\n", e); printf("length is %d\n", GetLength(S)); Pop(&S, &e); printf("Pop element is %d\n", e); TraverseStack(S, *visit); if (DestroyStack(&S)) { printf("\ndestroy_success\n"); } } }