It's nothing special. Do not operate on the original linked list, save each bit to a new list.
The program is roughly divided into four sections:
1. When L1 and L2 are not empty
2. When the L1 is not empty
3. When the L2 is not empty
4. When carry!=0, build a new node and put it at the end.
PublicListNode addtwonumbers (listnode L1, ListNode L2) {ListNode res=NewListNode (-1); ListNode Head=Res; if(L1 = =NULL|| L2 = =NULL) { returnRes.next; } intCarry = 0; while(L1! =NULL&& L2! =NULL) { intsum = l1.val + L2.val +carry; if(Sum >= 10) {sum-= 10; Carry= 1; } Else{Carry= 0; } ListNode NextNode=Newlistnode (sum); Res.next=NextNode; Res=Res.next; L1=L1.next; L2=L2.next; } while(L1! =NULL) { intsum = L1.val +carry; if(Sum >= 10) {sum-= 10; Carry= 1; } Else{Carry= 0; } ListNode NextNode=Newlistnode (sum); Res.next=NextNode; Res=Res.next; L1=L1.next; } while(L2! =NULL) { intsum = L2.val +carry; if(Sum >= 10) {sum-= 10; Carry= 1; } Else{Carry= 0; } ListNode NextNode=Newlistnode (sum); Res.next=NextNode; Res=Res.next; L2=L2.next; } if(Carry! = 0) {ListNode NextNode=NewListNode (1); Res.next=NextNode; } returnHead.next; }
Bug Record:
1. When you want to add, move res, but forget to move L1 and L2
Remember res = res.next, but forget L1 = l1.next, L2 = L2.next
2. Return at the end is returned Head.next not head
2. Add the Numbers