Leetcode 21 Solution

This article provides solution to leetcode question 21 (merge-two-sorted-lists)

https://leetcode.com/problems/merge-two-sorted-lists

Thinking Process

This is a basic question. Do remember to leverage the dummy head trick to avoid any unnecessary head processing logic.

Time & Space Complexity

Assuming N is the average length of the string

  • Time complexity: O(N)
  • Space complexity: O(1)

Solution

/** * 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) { ListNode* head = NULL; ListNode* p = NULL;
while (l1 || l2) { int v = INT_MAX; ListNode* next = NULL;
if (l1 && v >= l1->val) { next = l1; v = l1->val; }
if (l2 && v >= l2->val) { next = l2; v = l2->val; }
if (head == NULL) head = next;
if (p != NULL) p->next = next;
p = next;
if (next == l1) { l1 = l1->next; } else if (next == l2) { l2 = l2->next; } }
return head; } };