2. Add Two Numbers

/**
 * 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) {
        //利用先求得整数int结果的方法会造成溢出的错误
        int isOver=0;
        ListNode t1=l1;
        ListNode t2=l2;
        ListNode head=null;
        ListNode last=null;
        while(t1!=null&&t2!=null)
        {
            int temp=t1.val+t2.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t1=t1.next;
            t2=t2.next;
        }
        while(t1!=null)
        {
            int temp=t1.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t1=t1.next;
        }
        while(t2!=null)
        {
            int temp=t2.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t2=t2.next;
        }
        if(t1==null&&t2==null&&isOver==1)
        {
            ListNode t=new ListNode(1);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
        }
        return head;
    }
}

 

posted @ 2016-08-09 18:55  阿怪123  阅读(229)  评论(0编辑  收藏  举报