86. Partition List - Medium

前往題目

想法

  • 循環兩次,一次組小於x的,一次組大於等於x

思路

其實一次就好,一起組

  1. 宣告兩個新的list
  2. 走訪每個ListNode< x的放一組,>= x的放一組
  3. 兩組連起來

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/
作者
Simon Lai
發布於
2024年10月7日
許可協議