LeetCode86-分隔链表

题目链接

英文链接:https://leetcode.com/problems/partition-list/

中文链接:https://leetcode-cn.com/problems/partition-list/

题目详述

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

1
2
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

题目详解

  • 把链表拆分成两个链表,一个所有节点均小于 x,另一个所有节点均大于 x
  • 新建两个头结点,在遍历原链表的过程中进行拆分,链接到对应的链表上。
  • 最后把两个链表链起来。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class LeetCode_00086 {

public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return head;
}
ListNode smallHead = new ListNode(0);
ListNode largeHead = new ListNode(0);
ListNode p = smallHead;
ListNode q = largeHead;
ListNode cur = head;
while (cur != null) {
if (cur.val < x) {
p.next = cur;
p = p.next;
} else {
q.next = cur;
q = q.next;
}
cur = cur.next;
}
p.next = largeHead.next;
q.next = null;
return smallHead.next;
}
}