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的前面,而且相对顺序不能变
这个时候我们采用双指针法
runner1用于寻找最后一个比x小得元素,这里作为插入点(分割点)
runner2用于寻找应该插到插入点之后的元素
所以这里会出现三种情况
情况1: runner2的元素小于x,这个时候如果runner1和runner2指向同一个元素,说明还没有找到分割点,所以两个指针继续往前走就行了。
情况2: runner2的元素小于x,这个时候如果runner1和runner2指向不同的元素,说明runner1已经走到了分割点前,而runner2.next就是应该被插到分割点前。把runner2.next插入到分割点前就ok
情况3: runner2的元素大于x, 这个时候找到了分割点,只移动runner2就可以了。直到runner2.next小于分割点。然后按照情况2来操作就可以了
情况1和情况2:
if (runner2.next.val < x) {
if (runner1 == runner2) {
runner1 = runner1.next;
runner2 = runner2.next;
} else {
ListNode insert = runner2.next;
ListNode next = insert.next;
insert.next = runner1.next;
runner1.next = insert;
runner2.next = next;
runner1 = runner1.next;
}
}
情况3:
else
runner2 = runner2.next;
完整代码如下
public ListNode partition(ListNode head, int x) {
if (head == null)
return head;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode runner1 = helper;
ListNode runner2 = helper;
while (runner2 != null && runner2.next != null) {
if (runner2.next.val < x) {
if (runner1 == runner2) {
runner1 = runner1.next;
runner2 = runner2.next;
} else {
ListNode insert = runner2.next;
ListNode next = insert.next;
insert.next = runner1.next;
runner1.next = insert;
runner2.next = next;
runner1 = runner1.next;
}
} else
runner2 = runner2.next;
}
return helper.next;
}