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
.
先创建两个链表,分别存比x小的链表和比x大的链表,最后吧两个链表链接起来。
public static ListNode partition(ListNode head, int x){
ListNode small = new ListNode(0);
ListNode temp = small;
ListNode big = new ListNode(0);
big.next = head;
head = big;
while(head.next!=null){
if(head.next.val < x){
temp.next = head.next;
head.next = head.next.next;
temp = temp.next;
continue;
}
head = head.next;
}
temp.next = big.next;
return small.next;
}