标签:
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; }
版权声明:本文博客原创文章。博客,未经同意,不得转载。
【Leetcode】Partition List (Swap)
标签:
原文地址:http://www.cnblogs.com/bhlsheji/p/4628477.html