Lkstack.hnode
// 鏈棧的定義 typedef struct node { int data; struct node *next; }LkStk;
main.c算法
#include <stdio.h> #include "Lkstack.h" // 連接存儲實現棧的基本運算算法 // 1. 初始化,創建一個空棧 void InitStack(LkStk *LS) { LS = (LkStk *)malloc(sizeof(LkStk)); LS->next = NULL; } // 2. 判斷棧空 int EmptyStack(LkStk *LS) { if(LS->next == NULL) return 1; else return 0; } // 3. 進棧 void Push(LkStk *LS, int x) { LkStk *temp; temp = (LkStk *)malloc(sizeof(LkStk)); temp->data = x; temp->next = LS->next; // 指向棧頂節點 LS->next = temp; // 更新新的棧頂節點 } // 4. 出棧 int Pop(LkStk *LS) { LkStk *temp; if(!EmptyStack(LS)) { temp = LS->next; LS->next = temp->next; free(temp); return 1; } else return 0; } // 5. 取棧頂元素 int GetTop(LkStk *LS) { if(!EmptyStack(LS)) return LS->next->data; else return 0; }