面試題往往是經典問題的變體(如大數加法、鏈表反轉、LRU 快取),核心考察點不在於「背誦答案」,而在於:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct Node { int digit; struct Node *next; } Node;
Node* new_node(int d) {
Node *n = malloc(sizeof(Node));
n->digit = d; n->next = NULL; return n;
}
void free_list(Node *h) { while (h) { Node *t=h; h=h->next; free(t); } }
/* 從 stdin 讀取一行數字,建立反序鏈表(低位在頭) */
Node* read_number() {
int c; Node *head = NULL, *tail = NULL;
while ((c = getchar()) != EOF && isdigit(c)) {
Node *n = new_node(c - '0');
if (!head) head = tail = n;
else { tail->next = n; tail = n; }
}
return head ? head : new_node(0); // 至少一個節點
}
/* 大數相加:a + b,返回新鏈表 */
Node* add_lists(Node *a, Node *b) {
Node dummy; dummy.next = NULL;
Node *tail = &dummy;
int carry = 0;
while (a || b || carry) {
int sum = carry;
if (a) { sum += a->digit; a = a->next; }
if (b) { sum += b->digit; b = b->next; }
tail->next = new_node(sum % 10);
tail = tail->next;
carry = sum / 10;
}
return dummy.next;
}
/* 遞歸輸出(高位在前) */
void print_list(Node *h) {
if (h->next) print_list(h->next);
putchar(h->digit + '0');
}
int main() {
puts("輸入第一個整數:"); Node *n1 = read_number();
puts("輸入第二個整數:"); Node *n2 = read_number();
Node *sum = add_lists(n1, n2);
print_list(sum); putchar('\n');
free_list(n1); free_list(n2); free_list(sum);
return 0;
}
| 決策 | 理由 |
|---|---|
| 反序鏈表(低位在頭) | 對齊加法天然同步遍歷,無需先反轉或計算長度 |
| 哨兵節點 | 簡化頭節點特判,統一插入邏輯 |
| 單獨處理進位 | 迴圈條件 a || b || carry 自然涵蓋最高位進位 |
| 遞歸輸出 | 利用呼叫堆疊反轉順序,無需額外反轉鏈表 |
| 模組化函數 | 讀取/加法/輸出/釋放各司其職,易測試、易維護 |
掌握核心套路,保持冷靜表達,面試題自然不再是阻礙,而是你展現工程素養的機會。