. Merge Sorted Lists
- Total accepted:138746
- Total submissions:383218
- Difficulty:easy
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.
Idea: Add nodes recursively or iteratively.
Code:
Recursion:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* mergetwolists (listnode* L1, listnode*L2) { A if(!L1)returnL2; - if(!L2)returnL1; - if(l1->val<l2->val) { theL1->next=mergetwolists (l1->next,l2); - returnL1; - } -L2->next=mergetwolists (l1,l2->next); + return< - } +};
Iteration:
1 classSolution {2 Public:3listnode* mergetwolists (listnode* L1, listnode*L2) {4listnode* head=NewListNode (-1);5listnode* end=head;6 while(l1&&L2) {7 if(l1->val<l2->val) {8end->next=L1;9L1=l1->Next;Ten } One Else{ Aend->next=L2; -L2=l2->Next; - } theEnd=end->Next; - } - if(L1) { -end->next=L1; + } - Else{ +end->next=L2; A } at returnHead->Next; - } -};
Leetcode 21. Merge Sorted Lists