題目要求:
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
這道題其實是大數相加的處理,沒什麼難度,但需要注意以下幾點:
1.因爲存儲是反過來的,即數字342存成2->4->3,所以要注意進位是向後的;
2.鏈表l1或l2爲空時,直接返回,這是邊界條件,省掉多餘的操作;
3.鏈表l1和l2長度可能不同,因此要注意處理某個鏈表剩餘的高位;
4.2個數相加,可能會產生最高位的進位,因此要注意在完成以上1-3的操作後,判斷進位是否爲0,不爲0則需要增加結點存儲最高位的進位。
我的代碼如下,歡迎大牛指導交流~
AC,Runtime: 216 ms
//LeetCode_Add Two Numbers
//Written by zhou
//2013.11.1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *resList = NULL, *pNode = NULL, *pNext = NULL;
ListNode *p = l1, *q = l2;
int up = 0;
while(p != NULL && q != NULL)
{
pNext = new ListNode(p->val + q->val + up);
up = pNext->val / 10; //計算進位
pNext->val = pNext->val % 10; //計算該位的數字
if (resList == NULL) //頭結點爲空
{
resList = pNode = pNext;
}
else //頭結點不爲空
{
pNode->next = pNext;
pNode = pNext;
}
p = p->next;
q = q->next;
}
//處理鏈表l1剩餘的高位
while (p != NULL)
{
pNext = new ListNode(p->val + up);
up = pNext->val / 10;
pNext->val = pNext->val % 10;
pNode->next = pNext;
pNode = pNext;
p = p->next;
}
//處理鏈表l2剩餘的高位
while (q != NULL)
{
pNext = new ListNode(q->val + up);
up = pNext->val / 10;
pNext->val = pNext->val % 10;
pNode->next = pNext;
pNode = pNext;
q = q->next;
}
//如果有最高處的進位,需要增加結點存儲
if (up > 0)
{
pNext = new ListNode(up);
pNode->next = pNext;
}
return resList;
}
};