Merge sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should is made by splicing together the nodes of the and lists in sorted order.
Has you met this question in a real interview?Yes
Example
Given 1->3->8->11->15->null
, 2->null
return 1->2->3->8->11->15->null
.
For the original topic on Leetcode, see my previous blog, merge, Sorted Lists.
Solution One:
classSolution { Public: /** * @param listnode L1 is the head of the linked list * @param ListNode L2 is the head of the linked list * @return: ListNode head of linked list*/ListNode*mergetwolists (ListNode *l1, ListNode *L2) {ListNode*dummy =NewListNode (-1), *cur =dummy; while(L1 &&L2) { if(L1->val < l2->val) {cur->next =1l; L1= l1->Next; } Else{cur->next =L2; L2= l2->Next; } cur= cur->Next; } cur->next = L1?L1:l2; returnDummy->Next; }};
Solution Two:
classSolution { Public: /** * @param listnode L1 is the head of the linked list * @param ListNode L2 is the head of the linked list * @return: ListNode head of linked list*/ListNode*mergetwolists (ListNode *l1, ListNode *L2) { if(!L1)returnL2; if(!L2)returnL1; if(L1->val < l2->val) {L1->next = Mergetwolists (l1->Next, L2); returnL1; } Else{L2->next = mergetwolists (L1, l2->next); returnL2; } }};
Solution Three:
classSolution { Public: /** * @param listnode L1 is the head of the linked list * @param ListNode L2 is the head of the linked list * @return: ListNode head of linked list*/ListNode*mergetwolists (ListNode *l1, ListNode *L2) { if(!L1)returnL2; if(!L2)returnL1; ListNode*head = (L1->val < l2->val)?L1:l2; ListNode*nonhead = (L1->val < l2->val)?l2:l1; Head->next = Mergetwolists (head->Next, Nonhead); returnHead; }};
Solution Four:
class solution { public : /* * * @param listnode L1 is the head of the linked list * @param ListNode L2 is the head of the linked list * @ Return:listnode head of linked list L Istnode *mergetwolists (ListNode *l1, ListNode *l2) { if (!l1 | | (L2 && l1->val > L2->val)) swap (L1, L2); if (l1) L1->next = mergetwolists (l1-> next, L2); return L1; }};
[Lintcode] Merge Sorted Lists mixed insert ordered linked list