[LeetCode-interview algorithm classic-Java implementation] [002-Add Two Numbers (Two Numbers in a single-chain table)], leetcode -- java
[002-Add Two Numbers )]Original question
You are given two linked lists representing two non-negative numbers. the digits are stored in reverse order and each of their nodes contain a single digit. add the two numbers and return it as a linked list.
Input: (2-> 4-> 3) + (5-> 6-> 4)
Output: 7-> 0-> 8
Theme
There are two single-chain tables, representing two non-negative numbers. Each node represents a digit, and the number is stored reversely. That is, the first node represents the lowest bit, and the last node represents the highest bit. Calculate the sum of two numbers and return them in the form of a linked list.
Solutions
Process the two linked lists from the first one and add them. The result is divided by 10 to calculate the quotient, which serves as the carry of the next addition and records the remainder. As the base result, it is processed all the time, until all nodes are processed.
Code Implementation
/*** 002-Add Two Numbers (the sum of the Two Numbers in a single-chain table) * @ param l1 first count * @ param l2 second count * @ return result */public ListNode addTwoNumbers (ListNode l1, ListNode l2) {if (l1 = null) {return l2;} if (l2 = null) {return l1;} ListNode p1 = l1; ListNode p2 = l2; ListNode root = new ListNode (0 ); // header node ListNode r = root; root. next = l1; int carry = 0; // initial carry int sum; while (p1! = Null & p2! = Null) {sum = p1.val + p2.val + carry; p1.val = sum % 10; // standard result carry = sum/10; // carry r. next = p1; r = p1; // point to the last added node p1 = p1.next; p2 = p2.next;} if (p1 = null) {r. next = p2;} else {r. next = p1;} // The last addition has carry if (carry = 1) {// r. next is the first node to be added while (r. next! = Null) {sum = r. next. val + carry; r. next. val = sum % 10; carry = sum/10; r = r. next;} // after all the nodes are added and carry-in is complete, you must create a new node if (carry = 1) {r. next = new ListNode (1) ;}} return root. next ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/46905467]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.