這題看似簡單,但用到指標的技術,基本上就難在指標麻煩,跟if 的所有例外情況要排除會花時間想,還是有一些難度,雖然程式碼看似簡單。
原始題目:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode ans = new ListNode(0);
ListNode temp = ans; // 這樣宣告,temp則是繼承了ans的記憶體位置 call by address
while (p != null || q != null) {
int a = 0, b = 0, sum = 0, carry = 0;
if (p == null)
a = 0;
else
a = p.val;
if (q == null)
b = 0;
else
b = q.val;
sum = temp.val + a + b; // 要加原本已經進位的數值
if (sum >= 10) {
sum = sum % 10;
carry++;
}
if (p != null)
p = p.next;
if (q != null)
q = q.next;
temp.val = sum;
if (p != null || q != null || carry >= 1) { //3個條件都不符合就不要在串新的listnode了
temp.next = new ListNode(carry);
temp = temp.next;
}
}
return ans;
}
}
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記