LeetCode – Partition List (Java)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

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

For example, given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.

Java Solution

7 thoughts on “LeetCode – Partition List (Java)”

1. The result is correct indeed

2. This one might be easier to understand. C# code.

public Node PartitionList(Node head, T number)

{

var fakeHead1 = new Node(); //smaller ones

var fakeHead2 = new Node(); //bigger ones

while (p != null)

{

if (p.content.CompareTo(number) < 0)

{

fakeTail1.Next = p;

fakeTail1 = fakeTail1.Next;

p = p.Next;

fakeTail1.Next = null;

}

else

{

faketail2.Next = p;

faketail2 = faketail2.Next;

p = p.Next;

faketail2.Next = null;

}

}

}

3. Good answer, but if you’re going to swap the p and q values, the q value should be < num. You're skipping passed all the values num), it’ll work (tested and confirmed).

4. Here is a much simpler solution:

I’m iterating through with two iterators so I can change the current positions previous node’s next (no other way to access it in a singly linked list). Then whenever I encounter a value less than x, I append it in front of the head and set it as the new head. If the value is greater than or equal to x I just go onto the next value.

After reaching the end, I just return the new head.

(posted as screenshot because formatting gets messed up in a discuss text post)

5. Here is a much simpler solution:

6. The result gives 1->2->2->4->3->5. It is wrong.
It has to be 1->2->2->3->4->5.

Rule: all nodes less than x come before nodes greater than or equal to x.

Please correct me if I am wrong

7. Here is another version,

public void partitionList(Node start, int num){
Node p = start;
Node q = start;
while(q! = null){
while(p != null && p.value num)
q = q.next;
swapValue(p,q);
}
}