Medium 445题 Add Two Numbers II

来源:互联网 发布:淘宝手淘搜索怎么增加 编辑:程序博客网 时间:2024/06/07 14:31

Question:

You are given two linked lists representing two non-negative numbers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.


Solution:

/** * 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) {        List<Integer> n1=new ArrayList<Integer>();        while(l1!=null)        {            int tmp=l1.val;            n1.add(tmp);            l1=l1.next;        }        List<Integer> n2=new ArrayList<Integer>();        while(l2!=null)        {            int tmp=l2.val;            n2.add(tmp);            l2=l2.next;        }        ListNode head=new ListNode(0);        ListNode post=null;        int carry=0;        int i=n1.size()-1;        int j=n2.size()-1;        for(;i>=0||j>=0||carry!=0;i--,j--){            int cur=0;            if(i>=0)                cur+=n1.get(i);            if(j>=0)                cur+=n2.get(j);            cur+=carry;            carry=cur/10;            post=head.next;            ListNode tmp=new ListNode(cur%10);            head.next=tmp;            tmp.next=post;                    }        return head.next;    }}



0 0