Given two non-empty list to represent two non-negative integers. The highest number of bits are located in the list starting position. They each node only stores a single digit. The two numbers together will return a new list.
You may assume that in addition to the numbers 0, these two figures will not begin with a zero.
Advanced:
If the input list can not be changed how to deal with? In other words, you can not flip nodes in the list.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Solution 1:
public static class ListNode { Private int Val; Private ListNode Next; public ListNode ( int Val) { the this .val = Val; } } public static ListNode addTwoNumbers (ListNode L1, L2 ListNode) { / * inverted list * / ListNode R1 = Reverse (L1); / * inverted list * / ListNode R2 = Reverse (L2); / * dummy node to define a new linked list * / ListNode dumb = new new ListNode (0); / * Define a reference point to the dummy node * / ListNode R & lt = dumb; / * addend * / int the Add = 0 ; / * traversing two lists * / the while (R1 =! Null || R2 =! Null ) { int Val = the Add; the Add = 0 ; IF (! R1 = null ) { Val = Val + r1.val; R1 = r1.next; } IF (! R2 = null ) { Val = Val + r2.val; r2 = r2.next; } if (val >= 10) { val = val - 10; add = 1; } dumb.next = new ListNode(val); dumb = dumb.next; } if (add > 0) { dumb.next = new ListNode(add); } /*翻转新链表*/ return reverse(r.next); } public static ListNode reverse(ListNode head) { ListNode pre = null; while (head != null) { ListNode tmp = head.next; head.next = pre; pre = head; head = tmp; } return pre; }
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/add-two-numbers-ii