Interleave Two Linked Lists - Problem
You are given the heads of two linked lists list1 and list2.
Interleave the nodes by alternating between the two lists: take the first node from list1, then the first node from list2, then the second node from list1, then the second node from list2, and so on.
If one list is longer than the other, append the remaining nodes at the end.
Return the head of the interleaved linked list.
Input & Output
Example 1 — Equal Length
$
Input:
list1 = [1,3,5], list2 = [2,4,6]
›
Output:
[1,2,3,4,5,6]
💡 Note:
Alternate: 1(list1), 2(list2), 3(list1), 4(list2), 5(list1), 6(list2)
Example 2 — Unequal Length
$
Input:
list1 = [1,2], list2 = [10,20,30,40]
›
Output:
[1,10,2,20,30,40]
💡 Note:
Alternate: 1(list1), 10(list2), 2(list1), 20(list2), then remaining from list2: 30, 40
Example 3 — One Empty
$
Input:
list1 = [], list2 = [5,10]
›
Output:
[5,10]
💡 Note:
list1 is empty, so return list2 as-is
Constraints
- The number of nodes in both lists is in the range [0, 50].
- -100 ≤ Node.val ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code