002. Add Two Numbers
阿新 • • 發佈:2018-11-04
題目連結:https://leetcode.com/problems/add-two-numbers/description/
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
思路:
- 用兩個結點指標p1、p2分別指向這兩個連結串列L1、L2。
- 當p1、p2兩者指向非空時將p1、p2所指向結點的值val和進位數carNum相加。即sum = p1->val + p2->val + carNum; 其中進位數carNum
-
- 更新進位數的值:carNum = sum / 10;
- 獲得當前位的值:cur = sum % 10;
- 當p1 或 p2 兩者指向至少有一個為空時,上一步的操作終止。對非空的連結串列繼續進行後續操作。
編碼如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {}7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 ListNode *p1 = l1; 13 ListNode *p2 = l2; 14 15 ListNode *pHead = new ListNode(-1); 16 ListNode *p = nullptr; 17 18 19 int carNum = 0; // 進位數 20 21 while (nullptr != p1 && nullptr != p2) 22 { 23 int sum = p1->val + p2->val + carNum; 24 carNum = sum / 10; // 求進位數 25 int cur = sum % 10; // 當前位的數字 26 27 ListNode *pTemp = new ListNode(cur); 28 29 if (p == nullptr) 30 { 31 p = pTemp; 32 pHead->next = p; 33 } 34 else 35 { 36 p->next = pTemp; 37 p = pTemp; 38 } 39 40 p1 = p1->next; 41 p2 = p2->next; 42 } 43 44 45 while (nullptr != p1) 46 { 47 int sum = p1->val + carNum; 48 carNum = sum / 10; 49 int cur = sum % 10; 50 51 ListNode *pTemp = new ListNode(cur); 52 53 if (p != nullptr) 54 { 55 p->next = pTemp; 56 p = pTemp; 57 } 58 59 p1 = p1->next; 60 } 61 62 63 while (nullptr != p2) 64 { 65 int sum = p2->val + carNum; 66 carNum = sum / 10; 67 int cur = sum % 10; 68 69 ListNode *pTemp = new ListNode(cur); 70 71 if (p != nullptr) 72 { 73 p->next = pTemp; 74 p = pTemp; 75 } 76 77 p2 = p2->next; 78 } 79 80 if (carNum != 0) 81 { 82 ListNode *pTemp = new ListNode(carNum); 83 if (p != nullptr) 84 { 85 p->next = pTemp; 86 p = pTemp; 87 } 88 } 89 90 return pHead->next; 91 92 } 93 };