用鏈表實現棧(LIFO),包含結點定義、棧結構、四大核心操作、主函數測試、運行結果圖示。
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
// 結點
typedef struct Node {
int data;
struct Node *next;
} Node, *PNode;
// 棧
typedef struct Stack {
PNode top;
PNode bottom;
} Stack, *PStack;
void init_stack(PStack s) {
s->bottom = (PNode)malloc(sizeof(Node));
s->top = s->bottom;
s->bottom->next = NULL;
}
void push(PStack s, int val) {
PNode n = (PNode)malloc(sizeof(Node));
n->data = val;
n->next = s->top;
s->top = n;
printf("入棧:%d\n", val);
}
bool pop(PStack s, int *val) {
if (s->top == s->bottom) {
printf("棧空!\n");
return false;
}
PNode n = s->top;
*val = n->data;
s->top = n->next;
free(n);
return true;
}
void traverse(PStack s) {
if (s->top == s->bottom) {
printf("棧空!\n");
return;
}
PNode p = s->top;
printf("棧內元素:");
while (p != s->bottom) {
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Stack s;
int val;
init_stack(&s);
push(&s, 1); push(&s, 2); push(&s, 3);
push(&s, 4); push(&s, 5); push(&s, 6);
traverse(&s); // 6 5 4 3 2 1
if (pop(&s, &val)) {
printf("出棧:%d\n", val); // 6
traverse(&s); // 5 4 3 2 1
}
return 0;
}
入棧:1 入棧:2 入棧:3 入棧:4 入棧:5 入棧:6 棧內元素:6 5 4 3 2 1 出棧:6 棧內元素:5 4 3 2 1
free 釋放內存