题目
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
解答
解法一:小值移至前面
将值小于 x 的结点移动到前面。大于等于 x 的结点直接跳过。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode low = dummy;
ListNode pre = dummy;
while(pre.next != null) {
ListNode cur = pre.next;
if(cur.val < x) {
// 设置 pre 结点的 next 指针,顺便断开 cur 结点
pre.next = cur.next;
// 此时 low 指针会干扰到 pre 指针,需要重新修正 pre 指针
// 目的是为了让 pre 指针始终指向未遍历结点的前驱位置
if(low == pre) pre = cur;
// 将目标结点链接到前面
cur.next = low.next;
low.next = cur;
low = cur;
} else {
pre = pre.next;
}
}
return dummy.next;
}
}
结果
解法二:
将原来的链表分成两个链,最后再组装成一条链。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode p = dummy1;
ListNode q = dummy2;
while(head != null) {
if(head.val < x) {
p.next = head;
p = p.next;
} else {
q.next = head;
q = q.next;
}
head = head.next;
}
q.next = null;
p.next = dummy2.next;
return dummy1.next;
}
}