[LeetCode] Split a Circular Linked List

2674. Split a Circular Linked List

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 a circular 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<ListNode*> splitCircularLinkedList(ListNode* list) {
ListNode* runner = list;
while(runner->next != list) runner = runner->next;
runner->next = nullptr;
ListNode* slow = list, *fast = list;
while(fast->next != nullptr and fast->next->next != nullptr) {
fast = fast->next;
slow = slow->next;
if(fast->next != nullptr) fast = fast->next;
}
if(fast->next != nullptr) fast = fast->next;
ListNode* next = slow->next;
slow->next = list;
fast->next = next;
return {list, next};
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/30/PS/LeetCode/split-a-circular-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.