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
<Solution>Output: 7 -> 0 -> 8
這題是要相加兩個 link list,解題想法和 415. Add Stings 一樣,可以參考那篇文章
差別點只在於 data structure 不同,修改成操作 link list 的方式就可以了
code 如下
c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode *dummy = new ListNode(-1); | |
ListNode *currN = dummy; | |
int sum = 0, carry = 0; | |
while(l1 || l2) { | |
int a = (l1) ? l1->val : 0; | |
int b = (l2) ? l2->val : 0; | |
sum = a + b + carry; | |
carry = (sum > 9) ? sum / 10 : 0; | |
sum = (sum > 9) ? sum % 10 : sum; | |
currN->next = new ListNode(sum); | |
currN = currN->next; | |
if(l1) { | |
l1 = l1->next; | |
} | |
if(l2) { | |
l2 = l2->next; | |
} | |
} | |
if(carry != 0) { | |
currN->next = new ListNode(1); | |
} | |
return dummy->next; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
ListNode dummy = new ListNode(-1); | |
ListNode currN = dummy; | |
int sum = 0, carry = 0; | |
while(l1 != null || l2 != null) { | |
int a = (l1 != null) ? l1.val : 0; | |
int b = (l2 != null) ? l2.val : 0; | |
sum = a + b + carry; | |
carry = (sum > 9) ? sum / 10 : 0; | |
sum = (sum > 9) ? sum % 10 : sum; | |
currN.next = new ListNode(sum); | |
currN = currN.next; | |
if(l1 != null) { | |
l1 = l1.next; | |
} | |
if(l2 != null) { | |
l2 = l2.next; | |
} | |
} | |
if(carry != 0) { | |
currN.next = new ListNode(1); | |
} | |
return dummy.next; | |
} | |
} |
沒有留言:
張貼留言