LeetCode - Merge Two Sorted Lists

Merge Two Sorted Lists

2013.12.22 03:24

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Solution:

  This is a FAQ in IT interview. Make sure you don't new any node, and watch out for any special cases like NULL pointer or what.

  Time complexity is O(m + n), where m and n are the lengths of two lists. Space complexity is O(1).

Accepted code:

 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 class Solution {

10 public:

11     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {

12         // IMPORTANT: Please reset any member data you declared, as

13         // the same Solution instance will be reused for each test case.

14         if(l1 == nullptr){

15             return l2;

16         }else if(l2 == nullptr){

17             return l1;

18         }

19         

20         ListNode *l3, *head;

21         

22         if(l1->val <= l2->val){

23             l3 = l1;

24             l1 = l1->next;

25         }else{

26             l3 = l2;

27             l2 = l2->next;

28         }

29         l3->next = nullptr;

30         head = l3;

31         

32         while(l1 != nullptr && l2 != nullptr){

33             if(l1->val <= l2->val){

34                 l3->next = l1;

35                 l1 = l1->next;

36             }else{

37                 l3->next = l2;

38                 l2 = l2->next;

39             }

40             l3 = l3->next;

41             l3->next = nullptr;

42         }

43         

44         while(l1 != nullptr){

45             l3->next = l1;

46             l1 = l1->next;

47             l3 = l3->next;

48             l3->next = nullptr;

49         }

50         while(l2 != nullptr){

51             l3->next = l2;

52             l2 = l2->next;

53             l3 = l3->next;

54             l3->next = nullptr;

55         }

56         

57         return head;

58     }

59 };

 

 

你可能感兴趣的:(LeetCode)