#1669
Medium Algorithms Merge in between linked lists
Linked List
82.9% acceptance
Feb 25, 2026
2256
227
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn merge_in_between(
list1: Option<Box<ListNode>>,
a: i32,
b: i32,
list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
// Convert to Vec, splice, convert back
let mut v1 = vec![];
let mut cur = list1;
while let Some(node) = cur {
v1.push(node.val);
cur = node.next;
}
let mut v2 = vec![];
let mut cur = list2;
while let Some(node) = cur {
v2.push(node.val);
cur = node.next;
}
let a = a as usize;
let b = b as usize;
let merged: Vec<i32> = v1[..a].iter()
.chain(v2.iter())
.chain(v1[b + 1..].iter())
.cloned()
.collect();
// Build linked list from merged
let mut head = None;
for &val in merged.iter().rev() {
let mut node = Box::new(ListNode::new(val));
node.next = head;
head = Some(node);
}
head
}
// Helper to collect list values
pub fn to_vec(list: Option<Box<ListNode>>) -> Vec<i32> {
let mut v = vec![];
let mut cur = list;
while let Some(node) = cur {
v.push(node.val);
cur = node.next;
}
v
}
}