@requires_authorization@authorJohnsondu@create_time2015.7. Ten: *@url[Merge sorted lists] (https://leetcode.com/problems/merge-two-sorted-lists/)/******************* * Merge directly by size * Time complexity: O (n) * Spatial complexity: O (n) ******************//** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ class solution {public:listnode* mergetwolists (listnode* L1, listnode* L2) {if(L1 = = NULL)returnL2;if(L2 = = NULL)returnL1; ListNode *head =NewListNode (0); ListNode *ptr = head; while(L1 | | l2) {ListNode *cur = NULL;if(L1 = = NULL) {cur = L2; L2 = l2->next; }Else if(L2 = = NULL) {cur = L1; L1 = l1->next; }Else{if(l1->Val> l2->Val) {cur = L2; L2 = l2->next; }Else{cur = L1; L1 = l1->next; }} ptr->next = cur; PTR = ptr->next; }returnhead->next; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode" 21. Merge Sorted Lists