The title

Leetcode-cn.com/problems/ad…

You are given two non-empty linked lists representing two non-negative integers. Each digit is stored in reverse order, and only one digit can be stored per node.

You add the two numbers and return a linked list representing the sum in the same form.

You can assume that neither of these numbers will start with 0, except for the number 0.

Train of thought

There are two things to think about once you get your hands on this question:

1, reverse, do not need to reverse

I wrote an example by myself and suddenly found that I thought to the left, the reverse order just doesn’t need to send, because the list reads just from the beginning, the addition also starts from the bottom, so the reverse order is the same as the addition order is positive. You need to reverse the order

2, carry

Define a parameter cur to store the carry

code

There are several points in the code that you might miss and they are highlighted in the comments.

Class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null){return l2; } if (l2 == null){ return l1; } int cur=0,i=0,j=0,sum=0; ListNode l3 = new ListNode(0); ListNode a = l1,b=l2,c=l3; // While (a!); // While (a!); = null || b ! = null){ while(a ! = null || b ! = null || cur ! // I = a.val; // I = a.val; // j = b.val; i = a == null ? 0 : a.val; j = b == null ? 0 : b.val; sum = i + j + cur; Cur = sum > 9? 1:0; Math. Pow (10, I) ListNode k = new ListNode(sum%10); c.next = k; // Next is null if(a! = null){ a = a.next; } if(b ! = null){ b = b.next; } c = c.next; } return l3.next; }}Copy the code