鏈表題
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Bad case:
- 表頭指針保留柄慰。sentinel 有利于循環(huán)寫(xiě)法
2.鏈表長(zhǎng)度不等明刷, 迭代注意null的鏈表。
3.循環(huán)完帆竹,carry > 1 ,新Node赏枚。
循環(huán)寫(xiě)法
/**
* 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) {
int carry = 0;
int sums = 0;
ListNode sentinel = new ListNode(0);
ListNode curr = sentinel;
while (l1 != null || l2 != null) {
int s1 = (l1 != null) ? l1.val : 0;
int s2 = (l2 != null) ? l2.val : 0;
sums = carry + s1 + s2;
carry = sums / 10;
curr.next = new ListNode(sums % 10);
curr = curr.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry > 0) curr.next = new ListNode(carry);
return sentinel.next;
}
}
遞歸
- 注意遞歸時(shí)null沒(méi)有next
/**
* 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) {
return helper(l1, l2, 0);
}
public ListNode helper(ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null && carry == 0) {
return null;}
int sums = 0;
if (l1 != null) sums += l1.val;
if (l2 != null) sums += l2.val;
sums += carry;
ListNode curr = new ListNode(sums % 10);
curr.next = helper(l1 != null ? l1.next: null, l2 != null ? l2.next: null, sums/10);
return curr;
}
}