2674. Split a Circular Linked List
Explanation:
The problem asks us to split a circular linked list into two separate circular linked lists. We need to find the two halve points and then rewire the pointers accordingly.
Algorithm:
- Find the middle of the circular linked list using the slow and fast pointer technique.
- Break the circular link by setting the next pointer of the middle node to null.
- Set the head of the second half to the node next to the middle node.
- Update the next pointer of the last node of the first half to point to the head of the first half.
- Update the next pointer of the last node of the second half to point to the head of the second half.
Time Complexity: O(n) where n is the number of nodes in the circular linked list.
Space Complexity: O(1)
:
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode[] splitList(ListNode head) {
if (head == null || head.next == head) {
return new ListNode[] {head, null};
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != head && fast.next.next != head) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head2 = slow.next;
slow.next = null;
ListNode curr = head2;
while (curr.next != head) {
curr = curr.next;
}
curr.next = head2;
return new ListNode[] {head, head2};
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.