Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Linked Lists

Certification: Advanced Level Accuracy: 50% Submissions: 4 Points: 8

Write a C# function to merge two sorted linked lists and return the merged list. The new list should be made by splicing together the nodes of the first two lists and should also be sorted.

Example 1
  • Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
  • Output: [1, 1, 2, 3, 4, 4]
  • Explanation:
    • The two lists are merged in ascending order.
Example 2
  • Input: list1 = [], list2 = [0]
  • Output: [0]
  • Explanation:
    • The first list is empty, so the result is just the second list.
Constraints
  • The number of nodes in both lists is in the range [0, 50]
  • -100 ≤ Node.val ≤ 100
  • Both list1 and list2 are sorted in non-decreasing order
  • Time Complexity: O(n + m) where n and m are the lengths of the two lists
  • Space Complexity: O(1)
Linked ListHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a dummy head node to simplify edge cases
  • Compare the values of both list heads and add the smaller one to the result
  • Advance the pointer in the list that provided the smaller value
  • Handle cases where one list becomes empty before the other

Steps to solve by this approach:

 Step 1: Create a dummy head node to simplify edge cases.
 Step 2: Create a tail pointer to track the end of the merged list, initially pointing to the dummy head.
 Step 3: Compare the values of the current nodes in both lists while both lists have nodes.
 Step 4: Attach the node with the smaller value to the merged list and advance the pointer in that list.
 Step 5: Move the tail pointer to the newly added node.
 Step 6: After one list is exhausted, attach the remaining nodes from the other list (if any).
 Step 7: Return the merged list, starting from the node after the dummy head.

Submitted Code :