2014年2月9日星期日

LeetCoder - 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

/**
 * 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) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode cur = new ListNode(0);
        ListNode head = cur;
        boolean add1 = false;
        while(p1!=null || p2!=null) {
            if(add1) {
                cur.val += 1;
            }
            if(p1!=null) {
                cur.val += p1.val;
                p1 = p1.next;
            }
            if(p2!=null) {
                cur.val += p2.val;
                p2 = p2.next;
            }
            if(cur.val>=10) {
                cur.val %= 10;
                add1 = true;
            } else {
                add1 = false;
            }
            if(p1!=null || p2!=null || add1) {
                ListNode node = new ListNode(0);
                cur.next = node;
                cur = node;
            }
        }
        if(add1) {
            cur.val = 1;
        }
        return head;
    }
}


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode *p = &dummy;
        int val = 0;
        int carry = 0;
        while (l1 || l2) {
            val = carry;
            if(l1) {
                val += l1->val;
                l1 = l1->next;
            }
            if(l2) {
                val += l2->val;
                l2 = l2->next;
            }
            carry = val/10;
            val = val%10;
            p->next = new ListNode(val);
            p = p->next;
        }
        if(carry) {
            p->next = new ListNode(1);
        }
        return dummy.next;
    }
};

没有评论:

发表评论