考研C語言資料結構-鏈棧(棧的鏈式儲存實現)
阿新 • • 發佈:2022-05-07
#include <stdio.h> #include <stdlib.h> // 定義結點資料型別 typedef struct LNode { int data; // 資料域 struct LNode *next; // 指標域 }LNode, *LiStack; // 初始化鏈棧(帶頭結點) void initLiStack(LiStack &S) { S = (LNode *)malloc(sizeof(LNode)); S->next = NULL; } // 判斷棧空 bool isEmpty(LiStack S) { if(S->next == NULL) return true; return false; } // 入棧(頭插法LIFO) void push(LiStack &S, int e) { LNode *p = (LNode *)malloc(sizeof(LNode)); p->data = e; p->next = S->next; S->next = p; } // 出棧 bool pop(LiStack &S, int &e) { if(isEmpty(S)) return false; LNode *p = S->next; e = p->data; S->next = p->next; free(p); return true; } // 讀棧頂元素 bool getTop(LiStack S, int &e) { if(isEmpty(S)) return false; e = S->next->data; return true; } int main(void) { LiStack S; initLiStack(S); push(S, 1); push(S, 2); push(S, 3); push(S, 4); int e = -1; if(pop(S, e)) printf("出棧元素:%d\n", e); if(pop(S, e)) printf("出棧元素:%d\n", e); if(pop(S, e)) printf("出棧元素:%d\n", e); if(pop(S, e)) printf("出棧元素:%d\n", e); if(isEmpty(S)) printf("棧已空\n"); system("pause"); return 0; }