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
Test Instructions
Give you two lists, and find out the numbers of the two linked lists.
List 2, 4, 3 represents the number 324, the linked list 5, 6, 4 represents the number 465, and the results are also expressed in reverse of the list.
Ideas
1. Two lists are added from the beginning of the node, the single digit of the added node is saved in the new node, and the carry is saved in the carry.
2. If one of the linked lists has been traversed, the other linked list and carry are added until the traversal is complete.
3. Note that the final carry (carry) is equal to 1, and the new node is also required to store this carry, and then add it to the end of the list of results.
1 structlistnode* AddTwoNumbers (structlistnode* L1,structlistnode*L2) {2 3 intcarry=0;4 structlistnode* head =NULL;5 structlistnode* tail =NULL;6 while(L1 | |L2)7 {8 structlistnode* New_node = (structlistnode*)malloc(sizeof(structlistnode));9 if(l1!= NULL && l2!=NULL)Ten { OneNew_node->val = (l1->val+l2->val+carry)%Ten; Acarry = (L1->val+l2->val+carry)/Ten; -L1 = l1->Next; -L2 = l2->Next; the } - Else if(L1 = =NULL) - { -New_node->val = (l2->val+carry)%Ten; +carry = (L2->val+carry)/Ten; -L2 = l2->Next; + } A Else if(L2 = =NULL) at { -New_node->val = (l1->val+carry)%Ten; -carry = (L1->val+carry)/Ten; -L1 = l1->Next; - } - inNew_node->next =NULL; - if(Head = =NULL) to { +Head =New_node; -Tail =head; the } * Else $ {Panax NotoginsengTail->next =New_node; -Tail = tail->Next; the } + } A if(Carry) the { + structlistnode* New_node = (structlistnode*)malloc(sizeof(structlistnode)); -New_node->val =1; $New_node->next =NULL; $Tail->next =New_node; -Tail = tail->Next; - } the returnhead; -}View Code
leetcode.002 ADD Numbers