> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/5.linkedlist/221add-two-numbers-ii.md).

# 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 in`forward`order, 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**

Given`6->1->7 + 2->9->5`. That is,`617 + 295`.

Return`9->1->2`. That is,`912`.

## 2.Code

跟I 解法一样，不过是多了一个reverse list函数。

```
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);

            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);

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

            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;
```
