Tuesday, October 27, 2015

Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution: run time complexity is O(n), space complexity is O(n), 储存结果用的空间。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null)
            return l2;
        else if(l2 == null)
            return l1;
        
        ListNode result = new ListNode(-1);
        ListNode c1 = l1;
        ListNode c2 = l2;
        ListNode cR = result; 
        int carry = 0;
        
        while(c1 != null || c2 != null) {
            if(c1 != null) {
                carry += c1.val;
                c1 = c1.next;
            }
            if(c2 != null) {
                carry += c2.val;
                c2 = c2.next;
            }
            if(carry >= 10) {
                cR.next = new ListNode(carry - 10);
                carry = 1;
            }else {
                cR.next = new ListNode(carry);
                carry = 0;
            }
            cR = cR.next;
        }
        if(carry == 1)
            cR.next = new ListNode(1);
        
        return result.next;
    }
}

No comments:

Post a Comment