One minute
Leetcode 1669
1669. Merge In Between Linked Lists
The idea of this solution can be explained with a simple image:
- In image 1 we can see the input of
list1 = [0, 1, 2, 3, 4, 5]
,list2 = [10, 11, 12]
,a = 3
, andb = 4
. - We can iterate through
list2
and store the beginning and end of the list. - Then, we can iterate through
list1
and find the pos ofa - 1
. - Then, we can iterate through
list1
and find the pos ofb + 1
. - Then, the position of
a - 1
’s next pointer should be the beginning oflist2
, and the end oflist2
should be pointing to the position ofb + 1
inlist1
.
func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode {
counter := 0
cur := list1
start := list1
end := list2
for end.Next != nil {
end = end.Next
}
for cur != nil {
if counter == a - 1 {
start = cur
} else if counter == b + 1 {
start.Next = list2
end.Next = cur
break
}
counter++
cur = cur.Next
}
return list1
}
Read other posts