给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
题目含义是把一个链表分成两块,一块小于所给的数,一块大于,且每个块间的相对顺序不能改变。既然要求相对顺序不变,那就固定一块,把另一块提出来就好了,由于要连接两块,所以需要一块的尾和另一块的头,用p维护小于给定数值的节点块,而q则指向大于x的节点块的头部,遍历链表,小于x的节点通过尾插法插入小的节点块,大于等于的不作处理。贴代码:
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null)
return head;
ListNode h = new ListNode(0);
h.next = head;
ListNode cur = h;
while (cur.next != null && cur.next.val < x) {
cur = cur.next;
}
ListNode p = cur;
ListNode q = cur.next;
while (cur.next != null) {
if (cur.next.val < x) {
p.next = cur.next;
cur.next = cur.next.next;
p = p.next;
p.next = q;
}else
cur = cur.next;
}
return h.next;
}
}