【資料結構】棧的順序儲存結構 C語言實現
阿新 • • 發佈:2018-12-15
棧(stack),是一種線性儲存結構,它有以下幾個特點: 棧中資料是按照"後進先出(LIFO, Last In First Out)"方式進出棧的。 向棧中新增/刪除資料時,只能從棧頂進行操作。
基本操作 initStack(&S) destroyStack(&S) clearStack(&S) isStackEmpty(&S) getLength(&S) getTop(S, &e) pushStack(&S, e) popStack(&S, &e) stackTraverse(S, visit())
實現程式碼:
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define status int #define INIT_SIZE 100 #define INCRE_SIZE 10 typedef int elem; /* 順序棧 棧頂指標(top)棧底指標(base) 後進先出(last in first out)LIFO */ typedef struct { elem *top; elem *base; int stacksize; }SqStack; status initStack(SqStack * stack) { stack->base = (elem *)malloc(INIT_SIZE * sizeof(elem)); if(!stack->base) exit(-2); stack->top = stack->base; stack->stacksize = INIT_SIZE; printf("STACK---INIT---SUCCESS\n\n"); return 1; } int isStackEmpty(SqStack *stack) { if(stack->top == stack->base) return 1; return 0; } status pushStack(SqStack *stack, elem e) { if(stack->top - stack->base >= stack->stacksize){ stack->base = (elem *)realloc(stack->base ,(stack->stacksize + INCRE_SIZE) * sizeof(elem)); if(!stack->base) exit(-2); printf("STACK---PUSH---SUCCESS\n\n"); stack->top = stack->base + stack->stacksize; stack->stacksize += INCRE_SIZE; } *stack->top++ = e; return 1; } status getTop(SqStack *stack, elem *e) { if(stack->top == stack->base){ printf("空棧"); return 0; } //改變e的值 *e = *(stack->top-1); //返回棧頂元素 return 1; } //pop刪除S的棧頂元素,並用e放回其值 status popStack(SqStack *stack, elem * e) { if(!isStackEmpty(stack)){ *e = *(--stack->top); } return 1; } //返回棧的長度 status getlength(SqStack *stack) { return stack->top - stack->base; } status clearStack(SqStack *stack) { stack->top = stack->base; return 1; } //銷燬棧 status destoryStack(SqStack *stack) { if(!stack->base) free(stack->base); return 1; } //對每一個站內元素呼叫一個函式 status stackTraverse(SqStack *stack, void visit()) { if(!isStackEmpty(stack)){ elem *traver = stack->top; while(stack->base == stack->top--){ visit(*stack->top); } stack->top = stack->base + getlength(stack); } return 1; } int main(int argc, char *argv[]) { SqStack stack; initStack(&stack); //初始化棧 for(int i = 0; i < 101; i++){ pushStack(&stack, i); //入棧 } printf("length = %d\n", getlength(&stack)); for(int j = 0; j < 101; j++){ int e; popStack(&stack, &e); //出棧 printf("%d\t", e); } printf("\n"); if(isStackEmpty(&stack)) printf("Stack Empty!\n"); else printf("Stack is not Empty!\n"); printf("length = %d\n", getlength(&stack)); clearStack(&stack); //清空棧 // destoryStack(&stack); return 0; }