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; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1==null&&l2==null) return null;
        ListNode node = new ListNode(0) ;
        ListNode head = node;
        int carry = 0;
        while(l1!=null&&l2!=null)
        {
            int res = l1.val+l2.val+carry;
            node.next = new ListNode(res % 10);
            carry = res/10;
            l1 = l1.next;
            l2 = l2.next;
            node = node.next;
        }
        while(l1!=null){
            int res = l1.val+carry;
            node.next = new ListNode(res % 10);
            carry = res/10;
            l1 = l1.next;
            node = node.next;
        }
        while(l2!=null){
            int res = l2.val+carry;
            node.next = new ListNode(res % 10);
            carry = res/10;
            l2 = l2.next;
            node = node.next;        
        }
        if(carry!=0){
            node.next = new ListNode(carry);
        }
        
        return head.next;
        
    }
}

 

posted @ 2015-08-28 10:32  Hygeia  阅读(128)  评论(0编辑  收藏  举报