Skip to content

2674. Split a Circular Linked List 👍

  • Time:
  • Space:
 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
class Solution {
 public:
  vector<ListNode*> splitCircularLinkedList(ListNode* list) {
    ListNode* slow = list;
    ListNode* fast = list;

    // Point `slow` to the last node in the first half.
    while (fast->next != list && fast->next->next != list) {
      slow = slow->next;
      fast = fast->next->next;
    }

    // Circle back the second half.
    ListNode* secondHead = slow->next;
    if (fast->next == list)
      fast->next = secondHead;
    else
      fast->next->next = secondHead;

    // Circle back the first half.
    slow->next = list;

    return {list, secondHead};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public ListNode[] splitCircularLinkedList(ListNode list) {
    ListNode slow = list;
    ListNode fast = list;

    // Point `slow` to the last node in the first half.
    while (fast.next != list && fast.next.next != list) {
      slow = slow.next;
      fast = fast.next.next;
    }

    // Circle back the second half.
    ListNode secondHead = slow.next;
    if (fast.next == list)
      fast.next = secondHead;
    else
      fast.next.next = secondHead;

    // Circle back the first half.
    slow.next = list;

    return new ListNode[] {list, secondHead};
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def splitCircularLinkedList(self, list: Optional[ListNode]) -> List[Optional[ListNode]]:
    slow = list
    fast = list

    # Point `slow` to the last node in the first half.
    while fast.next != list and fast.next.next != list:
      slow = slow.next
      fast = fast.next.next

    # Circle back the second half.
    secondHead = slow.next
    if fast.next == list:
      fast.next = secondHead
    else:
      fast.next.next = secondHead

    # Circle back the first half.
    slow.next = list

    return [list, secondHead]