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
The topic said that there are two linked lists stored two non-negative integers, linked list of the number is inverted, each node of the list is only one digit, let you add up the two numbers and then in the form of the list of the problem returned.
For example: There are two non-negative integers 342 and 465, plus 807, then in the list is 2->4->3,5->6->4, the returned 807 of the linked list should be 7->0->8.
The idea of this problem is not difficult, is to traverse two linked lists, the number of points, the only thing to pay attention to is two numbers added more than 10 to carry the problem.
The code is as follows:
1 classsolution{2 Public:3listnode* addtonumbers (listnode* L1, listnode*L2) {4listnode* result_list =NewListNode (0);5listnode* Cursor_pointer =result_list;6 intCarry_num =0;7 while(true){8 if(L1! =NULL) {9Carry_num + = l1->Val;TenL1 = l1->Next; One } A if(L2! =NULL) { -Carry_num + = l2->Val; -L2 = l2->Next; the } -Cursor_pointer->val = carry_num%Ten; -Carry_num/=Ten; - if(L1! = NULL | | L2! = NULL | | carry_num >0){ +Cursor_pointer = (Cursor_pointer->next =NewListNode (0)); - } + Else{ A Break; at } - } - returnresult_list; - } -};
Leetcode problem 2.Add, Numbers