LeetCode. 链表求和 (Java)

Middle-Easy题
注意进位和最后一步容易忽略,最后需要判断有没有进位,进位就加一位值为1的尾节点。

/**
 * 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 candy = 0;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while (l1 != null || l2 != null){
            int val1 = (l1 == null) ? 0 : l1.val;
            int val2 = (l2 == null) ? 0 : l2.val;
            int sum = val1 + val2 + candy;
            if (sum >= 10)
                candy = 1;
            else
                candy = 0;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            if (l1 !=null)
                l1 = l1.next;
            if (l2 !=null)
                l2 = l2.next;
        }
        if (candy == 1){
            ListNode tmp = new ListNode(1);
            cur.next = tmp;
        }
        return head.next;
    }
}

你可能感兴趣的:(算法)