question:
You are given two linked lists representing two non-negative. The digits are stored in reverse order and all of their nodes a single contain. Add the two numbers and return it as a linked list.
Input: (2-> 4-> 3) + (5-> 6-> 4)
Output:7-> 0-> 8 examining:
The problem is to take the number of bits apart in reverse order in a linked list, requiring the calculation of two digits and return in the same way. The point of this question is the traversal of the linked list, he stored in reverse order the number, to reduce the complexity of the problem, imagine, from the two linked lists at the same time take out a number, such as the first, these two digits are the number of digits, directly add can be, get the number to see whether there is a carry, the value of the values down.
My idea is to put the number of two linked lists to take out, not out of a number added and then add to carry, and 10 for the remainder, save to another list of nodes, take the whole get carry, save up,
Loop until the two linked lists are empty. Problem Solving:
/** * 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) {if (L1 = null && Amp
L2 = = null) {return null;
} ListNode Lhead;
ListNode L = new ListNode (0);
Lhead = l;
int flag=0;
while (L1!=null | | l2!=null) {ListNode lnext = new ListNode (0);
int a = L1==null?0:l1.val;
int b = L2==null?0:l2.val;
Lnext.val = (a+b+flag)%10;
Flag = (A+b+flag)/10;
L.next = Lnext;
L = l.next;
L1 = L1==null?null:l1.next;
L2 = L2==null?null:l2.next;
if (flag!= 0)//If there is a carry, add the node to the {ListNode Lnext = new ListNode (0);
Lnext.val = Flag;
L.next = Lnext; Return LheaD.next; }
}
This problem-solving thinking is relatively normal, is based on life experience to solve problems, there is no complex algorithm, ranked center.