A-036● Day 362026.06.11easyleetcode #21neetcode150
Merge Two Sorted Lists
#linked-list#recursion
01
Problem
· problemYou are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
constraints
- · Number of nodes in both lists: [0, 50]
- · -100 ≤ Node.val ≤ 100
- · Both lists are sorted in non-decreasing order
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Do we need to create new nodes or rearrange existing ones?
- ☐What should we return if both lists are empty?
- ☐Can the lists contain duplicate values?
- ☐Are the input lists guaranteed to be sorted?
- ☐Can we modify the original lists?
- ☐Do we need to sort the merged list after combining?
- ☐Should we allocate extra nodes for the merged list?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize dummy node
○
dummy = node = ListNode()
○
dummy = ListNode(0)
○
node = None
step 2· Loop while both lists have nodes
○
while list1 and list2:
○
while list1 or list2:
○
while True:
step 3· Compare and attach the smaller value│ nested
○
if list1.val < list2.val:
○
if list1.val <= list2.val:
○
if list1.val > list2.val:
step 4· Advance the merged list pointer│ nested
○
node = node.next
○
dummy = dummy.next
○
node.next = node.next.next
step 5· Attach remaining nodes
○
node.next = list1 or list2
○
return list1 or list2
○
node.next = list1 + list2
step 6· Return the merged list head
○
return dummy.next
○
return dummy
○
return node
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[1,2,4] [1,3,4]→
[1,1,2,3,4,4]
case 2
[] []→
[]
case 3
[] [0]→
[0]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.