The questions are as follows:
Two non-empty linked lists are given to represent two non-negative integers. The number of digits is stored in reverse order. Each node only stores a single number. Returns a new Linked List by adding the two numbers.
You can assume that all the numbers except 0 do not start with zero.
Example:
Input: (2-> 4-> 3) + (5-> 6-> 4) Output: 7-> 0-> 8 cause: 342 + 465 = 807
Train of Thought Analysis:
Because we need to traverse the values of each linked list node, since it is traversal, we certainly need to use a loop, but we do not know the length of the linked list, so we use the while loop for iteration, we need to use the concept of an endpoint. When the linked list comes into contact with the last node, the loop stops.
The code I wrote myself is as follows:
Public listnode addtwonumbers (listnode L1, listnode l2) {// set a flag variable Boolean flag = false outside the loop because of the bitwise situation. // The start linked list, set a pointer to return the head of the linked list. listnode = new listnode (0); listnode first = listnode; while (L1! = NULL & L2! = NULL) {listnode. val = l1.val + l2.val; If (FLAG) {flag = false; listnode. val ++;} If (listnode. val> = 10) {listnode. val-= 10; flag = true;} If (l1.next! = NULL | l2.next! = NULL) {listnode. Next = new listnode (0); listnode = listnode. Next;} L1 = l1.next; L2 = l2.next;} while (L1! = NULL) {listnode. val = l1.val; If (FLAG) {flag = false; listnode. val ++;} If (listnode. val> = 10) {listnode. val-= 10; flag = true;} If (l1.next! = NULL) {listnode. Next = new listnode (0); listnode = listnode. Next;} L1 = l1.next;} while (L2! = NULL) {listnode. val = l2.val; If (FLAG) {flag = false; listnode. val ++;} If (listnode. val> = 10) {listnode. val-= 10; flag = true;} If (l2.next! = NULL) {listnode. next = new listnode (0); listnode = listnode. next;} L2 = l2.next;} // After the iteration is complete, determine whether there is a carry if (FLAG) {listnode. next = new listnode (1); listnode = listnode. next;} return first ;}
After the submission, I checked the reference code and found that the conciseness and details can be improved.
Reference code:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next;}
Leetcode 2: Add two numbers