221.Add Two Numbers II

1.Description(Medium)

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored inforwardorder, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given6->1->7 + 2->9->5. That is,617 + 295.

Return9->1->2. That is,912.

Tags

Linked List High Precision

2.Code

跟167 add two numbers 一样,只不过加了reverse基本操作

 public ListNode addLists2(ListNode l1, ListNode l2) {
        if(l1==null && l2==null){
            return null;
        }

        ListNode dummy=new ListNode(0);
        ListNode current=dummy;
        int carry=0;
        l1=reverse(l1);
        l2=reverse(l2);
        while(l1!=null && l2!=null){
            int sum=l1.val+l2.val+carry;
            carry=sum/10;
            current.next=new ListNode(sum%10);

            l1=l1.next;
            l2=l2.next;
            current=current.next;
        }
        while(l1!=null){
            int sum=l1.val+carry;
            carry=sum/10;
            current.next=new ListNode(sum%10);

            l1=l1.next;
            current=current.next;
        }
        while(l2!=null){
            int sum=l2.val+carry;
            carry=sum/10;
            current.next=new ListNode(sum%10);

            l2=l2.next;
            current=current.next;
        }
        if(carry!=0){
            current.next=new ListNode(carry);
        }
        return reverse(dummy.next);
    } 

    public ListNode reverse(ListNode head){
        ListNode prev=null;
        while(head!=null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }

Last updated