Leetcode Problem 21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

Leetcode Solutions

Iterative Merge of Two Sorted Linked Lists

  1. Initialize a dummy node called prehead to serve as the starting point of the merged list.
  2. Create a pointer prev and set it to the prehead.
  3. While both list1 and list2 have nodes to compare: a. Compare the values of the current nodes of list1 and list2. b. If list1's value is less than or equal to list2's, attach list1 to prev and move list1 to its next node. c. Otherwise, attach list2 to prev and move list2 to its next node. d. Move prev to its next node (the node we just attached).
  4. Once we reach the end of one list, attach the remaining part of the other list to prev.
  5. Return prehead.next, which is the head of the merged list.
UML Thumbnail

Recursive Merge of Two Sorted Linked Lists

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...