Problem Analysis:
We go through two lists to get the value of each bit, two values plus the previous one carry value (0 or 1) modulo 10 is the value of that bit, divided by 10 is the carry value to the high (0 or 1).
Since two lists can be not the same length, so in time to judge, once null, the value of the bit will become 0.
There is a particular situation, such as: 1->1->1->null, 9->8->8->null, the final result for 0->0->0->1->null, need to retain the highest bit.
And 1->1->1->null, 9->8->7->null, the end result for 0->0->9->null, then do not need to retain the highest bit, and finally should add a judgment.
Problem solving:
Public classSolution { PublicListNode addlists (listnode L1, ListNode L2) {ListNode Prelistnode=NewListNode (0); ListNode Nowlistnode=NewListNode (0); ListNode Resultlistnode=NULL; intval = 0;//the number of the current position intadd = 0;//Rounding while(L1! =NULL|| L2! =NULL) { //the value of the bitval = ((L1 = =NULL? 0:l1.val) + (L2 = =NULL? 0:l2.val) + Add)% 10; //for the next one, the resulting roundingAdd = ((L1 = =NULL? 0:l1.val) + (L2 = =NULL? 0:l2.val) + Add)/10; L1= L1 = =NULL? L1:l1.next;//determine if the L1 is moving downL2 = L2 = =NULL? L2:l2.next;//determine if the L2 is moving down//Nowlistnode and Nowlistnode are used to produce a new linked list.Nowlistnode.val =Val; if(Resultlistnode = =NULL) {Resultlistnode=Nowlistnode; } Prelistnode=Nowlistnode; Nowlistnode=NewListNode (0); Prelistnode.next=Nowlistnode; } //Finally, one more judgment, because there is a possibility, two linked list as long, the last one went up into aval = ((L1 = =NULL? 0:l1.val) + (L2 = =NULL? 0:l2.val) + Add)% 10; Add= ((L1 = =NULL? 0:l1.val) + (L2 = =NULL? 0:l2.val) + Add)/10; Nowlistnode.val=Val; //if the last one goes up again, the new last one is not 0, should be kept, otherwise 0, should be discarded if(Nowlistnode.val = = 0) {Prelistnode.next=NULL; } returnResultlistnode; }}classListNode {intVal; ListNode Next; ListNode (intx) {val=x; Next=NULL; }}
Sum of "Lintcode" linked list