A problem involving circular-list
Deceiving problem: just need to split a circular linked-list into two. Problem is that we first need to count how many elements are there, and there may be duplicates. Easy solution is to change the first element to something unique, like -1. Then it becomes straightforward. Code is below, cheers, ACC.
Split a Circular Linked List - LeetCode
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.
Example 1:
Input: nums = [1,5,7] Output: [[1,5],[7]] Explanation: The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half.
Example 2:
Input: nums = [2,6,1,5] Output: [[2,6],[1,5]] Explanation: The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half.
Constraints:
- The number of nodes in
list
is in the range[2, 105]
0 <= Node.val <= 109
LastNode.next = FirstNode
whereLastNode
is the last node of the list andFirstNode
is the first one
public ListNode[] SplitCircularLinkedList(ListNode list) { ListNode[] retVal = new ListNode[2]; if (list == null) return retVal; int tempFirst = list.val; list.val = -1; int count = 0; bool first = true; for (ListNode temp = list; first || temp.val != list.val; temp = temp.next) { first = false; count++; } retVal[0] = null; ListNode t0 = null; retVal[1] = null; ListNode t1 = null; for (int i = 0; i < count; i++) { if ((count % 2 == 0 && i < count / 2) || (count % 2 == 1 && i <= count / 2)) { if (retVal[0] == null) { retVal[0] = new ListNode(list.val); t0 = retVal[0]; } else { t0.next = new ListNode(list.val); t0 = t0.next; } } else { if (retVal[1] == null) { retVal[1] = new ListNode(list.val); t1 = retVal[1]; } else { t1.next = new ListNode(list.val); t1 = t1.next; } } list = list.next; } t0.next = retVal[0]; t1.next = retVal[1]; retVal[0].val = tempFirst; return retVal; }
Comments
Post a Comment