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
.
思路:用指针 P 遍历这个队列,每当值有大于或等于 x 的节点,我们就让 P 停下来,
然后设置一个指针 Q 寻找从 P 以后的第一个值小于 x 的 节点。例如,当 P 停在 4
时,Q 应当停在 2 ;然后我们设置个指针 swap 从 P 走到 Q,交换 swap 节点和 Q
节点的值。
// 看leetcode 评论里另一个思路是把小于 x 的所有元素串成一条链,大于等于 x 的
串成另一条链,最后两链一接,完事。。。。。妙啊!
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode partition(ListNode head, int x) { 11 if (head == null || head.next == null) 12 return head; 13 ListNode p = head; 14 while (p != null){ 15 if (p.val >= x){ 16 ListNode q = p; 17 while (q != null){ 18 if (q.val < x) 19 break; 20 q = q.next; 21 } 22 if (q == null) 23 break; 24 ListNode swap = p; 25 while (swap != q){ 26 int tmp = swap.val; 27 swap.val = q.val; 28 q.val = tmp; 29 swap = swap.next; 30 } 31 } 32 p = p.next; 33 } 34 return head; 35 } 36 }