標籤:
question:You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
中文描述:給你兩個鏈表代表兩個非負的數字。每個數字儲存在倒轉順序的列表中,並且每個節點包含一個十進位的數,將這兩個數相加並返回該格式的鏈表。
example的意思: 342 + 465 = 807
分析:由於第一個節點代表第一位,我們可以採用進位相加的方法。
有3種可能出現的情況。
1、兩個鏈表一樣長,這時我們要注意最高為位產生進位,如果產生進位,則要在相加的結果上增加一個為1的node節點。
2、第一個鏈表長度大於第二個鏈表,將第一個鏈表超出的部分增加到sum鏈表中,注意與第二個鏈表最高位相加產生的進位。
3、第二個鏈表長度大於第一個鏈表,與情況二類似,不再贅述。
LeetCode代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ int carry = 0; // 進位 struct ListNode *p1, *p2; struct ListNode *p, *q; p = q = NULL; p1 = l1; p2 = l2; int current; int flag = 1; struct ListNode *node; while(p1 && p2) // 同步遍曆鏈表 { current = p1->val + p2->val; current += carry; // 加上進位 if(current >= 10) // 產生進位 { current -= 10; carry = 1; } else carry = 0; node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->val = current; node->next = NULL; if(flag) // 第一次添加節點 { p = node; q = node; flag = 0; } else { q->next = node; q = node; } p1 = p1->next; p2 = p2->next; } if(p1) // 鏈表1長度大於鏈表2 { while(p1) { current = p1->val + carry; if(current >= 10) { current -= 10; carry = 1; } else carry = 0; node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->val = current; node->next = NULL; q->next = node; q = node; p1 = p1->next; } } if(p2)// 鏈表2長度大於鏈表1 { while(p2) { current = p2->val + carry; if(current >= 10) { current -= 10; carry = 1; } else carry = 0; node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->val = current; node->next = NULL; q->next = node; q = node; p2 = p2->next; } } if(carry == 1) // 鏈表1長度等於鏈表2,並且最高位相加產生進位 { node = (struct ListNode *)malloc(sizeof(struct ListNode)); node->val = 1; node->next = NULL; q->next = node; q = node; } return p;}
如果有更好的方法,希望不吝賜教!
2、LeetCode--Add Two Numbers