86. Partition List - Medium
前往題目
想法
- 循環兩次,一次組小於
x
的,一次組大於等於x
的
思路
其實一次就好,一起組
- 宣告兩個新的
list
- 走訪每個
ListNode
,< x
的放一組,>= x
的放一組 - 兩組連起來
Code
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode left = new ListNode(-101), right = new ListNode(-101);
ListNode leftHead = left, rightHead = right;
// Go through all the elements
while (head != null) {
if (head.val < x) {
left.next = head;
left = left.next;
} else {
right.next = head;
right = right.next;
}
// Move to the next element
head = head.next;
}
// Connect 2 lists
left.next = rightHead.next;
right.next = null;
return leftHead.next;
}
}
86. Partition List - Medium
https://f88083.github.io/2024/10/07/86-Partition-List-Medium/