本題要求將兩個非負整數以逆序鏈表形式存儲(每個節點一位數字),模擬豎式加法計算並返回結果鏈表。文章詳細拆解進位邏輯、邊界處理及內存管理,提供優化版 C 語言實現。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *phead = NULL; // 結果鏈表頭
struct ListNode *curp = NULL; // 結果鏈表尾
struct ListNode *cur1 = l1, *cur2 = l2;
int carry = 0; // 進位
while (cur1 || cur2) {
int v1 = cur1 ? cur1->val : 0;
int v2 = cur2 ? cur2->val : 0;
int sum = v1 + v2 + carry;
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = sum % 10;
node->next = NULL;
carry = sum / 10;
if (!phead) {
phead = curp = node;
} else {
curp->next = node;
curp = node;
}
if (cur1) cur1 = cur1->next;
if (cur2) cur2 = cur2->next;
}
if (carry) { // 處理最高位進位
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 1;
node->next = NULL;
curp->next = node;
}
return phead;
}
本題考察鏈表基本操作與初等數學模擬。關鍵在於簡潔處理不同長度鏈表、正確維護進位、規範構建新鏈表。優化版代碼邏輯清晰、分支極少,是面試與刷題的推薦寫法。