lihe/Leetcode

Leetcode_2_Add Two Numbers

lihe opened this issue · 0 comments

lihe commented

Add Two Numbers

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.

算法思路:

按照手算两个数字和那样,从最低位开始相加,和超过10即进位。

  • 创立新列表。
  • 将进位carry初始化为0。
  • 将p和q分别指向l1和l2的头部。
  • 遍历列表l1和l2直到它们的尾部。
    • x设为节点p的值,y设为节点y的值,如果x、y已经到达l1和l2的尾部,则将x或y置零。
    • sum = x + y + carry
    • carry = sum /10
    • 创建一个数值为 (sum mod 10)的新结点,并将其设置为当前结点的下一个结点,然后将当前结点前进到下一个结点。
    • 同时,将 pq 前进到下一个结点。
  • 检查 carry = 1 是否成立,如果成立,则向返回列表追加一个含有数字 11 的新结点。
  • 返回新列表的头节点。
/**
 * 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 dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, cur = dummyHead;

        int carry = 0;

        while(p != null || q != null){
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;

            int sum = carry + x + y;

            carry = sum / 10;

            cur.next = new ListNode(sum % 10);

            cur = cur.next;

            if(p != null) p = p.next;
            if(q != null) q = q.next;
        }
        if(carry > 0)
            cur.next = new ListNode(carry);

        return dummyHead.next;
    }
}