Problem
Given a circular linked list list
of positive integers, your task is to split it into 2 circular linked lists so that the first one contains the first half of the nodes in list
(exactly ceil(list.length / 2)
nodes) in the same order they appeared in list
, and the second one contains the rest of the nodes in list
in the same order they appeared in list
.
Return an array answer of length 2 in which the first element is acircular linked list representing the first half and the second element is a circular linked list representing the second half.
A circular linked list is a normal linked list with the only difference being that the last node’s next node, is the first node.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
- The number of nodes in
list
is in the range[2, 10^5]
0 <= Node.val <= 10^9
LastNode.next = FirstNode
whereLastNode
is the last node of the list andFirstNode
is the first one
Solution
Method 1 – Two Pointers (Fast and Slow)
Intuition
To split a circular linked list into two halves, we can use the classic fast and slow pointer approach to find the midpoint. This allows us to determine where to break the list, and then we can adjust the next pointers to form two new circular lists.
Approach
- Use two pointers, slow and fast, to find the midpoint of the circular list.
- Move fast by two steps and slow by one step until fast reaches the end.
- The node after slow is the start of the second half.
- Break the list into two by updating the next pointers so that both halves are circular.
- Return the heads of the two new lists.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the number of nodes, as we traverse the list once. - 🧺 Space complexity:
O(1)
, only pointers are used.