棧是「先進後出」(LIFO)結構,靜態數組實現最直觀:一個數組存數據,一個 top 索引指向棧頂。適合最大容量可預估、極度追求速度、無動態分配環境(如單片機)的場景。
#define STACK_SIZE 50 static int stack[STACK_SIZE]; static int top_element = -1; // -1 代表空棧
isEmptyint isEmpty() { return top_element == -1; }
isFullint isFull() { return top_element == STACK_SIZE - 1; }
pushvoid push(int value) {
if (!isFull()) stack[++top_element] = value;
else printf("棧滿,壓入失敗\n");
}
popvoid pop() {
if (!isEmpty()) top_element--;
else printf("棧空,彈出失敗\n");
}
top(不修改結構)int top() {
if (!isEmpty()) return stack[top_element];
return -32768; // 約定錯誤值
}
printStack(從頂向下)void printStack() {
printf("靜態數組棧內容:");
if (top_element == -1) { printf("空棧\n"); return; }
for (int i = top_element; i >= 0; i--) printf("%d ", stack[i]);
printf("\n");
}
int main() {
push(4); push(6); push(1); push(9); push(2); push(8);
printStack(); // 8 2 9 1 6 4
pop(); pop(); pop(); pop(); // 彈出 4 個
printf("經過 pop 後:"); printStack(); // 6 4
printf("棧頂元素: %d\n", top()); // 6
return 0;
}
pop vs top| 操作 | 修改 top_element | 返回值 | 用途 |
|---|---|---|---|
pop | 是 (--) | 無 | 移除棧頂 |
top | 否 | 棧頂值 | 只讀檢查 |
STACK_SIZE,溢出只能報錯。realloc 動態數組或單鏈表(見前文)。GitHub:Stack_StaticArray,含 Makefile 可直接 make run。