2.Add Two Numbers - linked list

链表题

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Bad case:

  1. 表头指针保留。sentinel 有利于循环写法
    2.链表长度不等, 迭代注意null的链表。
    3.循环完,carry > 1 ,新Node。

循环写法

/**
 * 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;
    }
}

递归

  • 注意递归时null没有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;
    }
}

你可能感兴趣的:(2.Add Two Numbers - linked list)