Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Subscribe to see which companies asked this question
Solution 1: Recursion. First compare head node size, if L2->val>l1->val, return mergetwolists (L2,L1); otherwise (1) if l1->next!=null, compare l1->next-> The size of Val and L2->val, so that the order of the first two elements can be determined,
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(L1 = = NULL)returnL2; if(L2 = = NULL)returnL1; if(L1->val <= l2->val) { if(L1->next! = NULL && l1->next->val <= l2->val) {ListNode* node = mergetwolists (l1->next->Next, L2); L1->next->next =node; } Else if(L1->next! = NULL && l1->next->val > l2->val) {ListNode* node = mergetwolists (L1->next, l2->next); L2->next =node; L1->next =L2; } ElseL1->next =L2; returnL1; } Else returnmergetwolists (L2, L1); }};
Solution 2: Iteration. Create a new pointer to help, and then traverse L1 and L2 to link the smaller links to the help behind. Finally, the next node of help is returned as the head node. Note that two linked lists may be of different lengths to link the last remaining elements of the long list to the new linked list.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) { if(L1 = = NULL)returnL2; if(L2 = = NULL)returnL1; ListNode* Help =NewListNode (0); ListNode* head =Help ; while(L1! = NULL && L2! =NULL) { if(L1->val <= l2->val) { Help->next =L1; L1= l1->Next; } Else{ Help->next =L2; L2= l2->Next; } Help= help->Next; } if(L1! = NULL) Help->next =L1; if(L2! = NULL) Help->next =L2; returnHead->Next; }};
[Leetcode]80. Merge two Sorted lists combined with two sorted lists