You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
Problem-Solving ideas: You can refer to the binary number add the problem, but this topic is different from left to right, that is, carry the right to move (enough wonderful), so simple, direct shift on the line, you need to pay attention to the structure of the list and the null pointer. With the help of dummy nodes and double pointers, it is easy to solve the problem, one is responsible for the shift, and one is responsible for storage.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {val = x;}
* *
/public class Solution {public
ListNode addtwonumbers (listnode L1, ListNode L2) {
ListNode pre= New ListNode (0);
ListNode Head=pre;
int carry=0;
while (l1!=null| | l2!=null| | carry!=0) {
listnode curr=new listnode (0);
int sum= (l1==null?0:l1.val) + (l2==null?0:l2.val) +carry;
CARRY=SUM/10;
curr.val=sum%10;
pre.next=curr;//equivalent to storage, assignment
pre=curr;//shift
l1= (l1==null?null:l1.next);
L2= (L2==null?null:l2.next);
}
return head.next;
}
}
If the title changes, the carry is from right to left, this time you have to consider the reverse of the list ....