86 Partition List

1. Question

Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.

You should preserve the original relative order of the nodes in each of the two partitions.

For example, Given1->4->3->2->5->2andx= 3, return1->2->2->4->3->5.

2. Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode less = new ListNode(0);
        ListNode equalOrMore = new ListNode(0);
        ListNode p1 = less;
        ListNode p2 = equalOrMore;

        ListNode curNode = head;

        while (curNode != null) {
            if (curNode.val < x) {
                p1.next = curNode;
                p1 = p1.next;
            }
            else {
                p2.next = curNode;
                p2 = p2.next;
            }
            curNode = curNode.next;
        }

        p2.next = null;
        p1.next = equalOrMore.next;
        return less.next;
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated