题目:
给你一个链表的头节点 head
和一个特定值 x
,请你对链表进行分隔,使得所有 小于 x
的节点都出现在 大于或等于 x
的节点之前。你应当 保留 两个分区中每个节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2
输出:[1,2
思路分析:
这道题目比较简单,它是一道分隔链表的题目,需要将小于 x 的节点和大于等于 x 的节点分隔开来,并且保留它们在原始链表中的相对顺序。我们可以通过创建两个新的链表,分别存放小于 x 的节点和大于等于 x 的节点,这里使用尾插法,因为要保证相对顺序,最后将这两个链表合并起来即可。
具体代码及详细注释如下:
class Solution {
public ListNode partition(ListNode head, int x) {
// 创建两个虚拟头节点,分别用于存放小于 x 的节点和大于等于 x 的节点
ListNode smallerXNode = new ListNode(0); // 小于 x 的节点链表头节点
ListNode NoSmallerXNode = new ListNode(0); // 大于等于 x 的节点链表头节点
// 创建两个指针,用于遍历两个分区的链表
ListNode smallerp = smallerXNode; // 小于 x 的节点链表指针
ListNode nosmallerq = NoSmallerXNode; // 大于等于 x 的节点链表指针
// 遍历原始链表
while (head != null) {
if (head.val < x) {
// 如果当前节点值小于 x,则将其连接到小于 x 的节点链表
smallerp.next = head;
smallerp = smallerp.next;
} else {
// 如果当前节点值大于等于 x,则将其连接到大于等于 x 的节点链表
nosmallerq.next = head;
nosmallerq = nosmallerq.next;
}
head = head.next; // 移动到下一个节点
}
// 将两个分区合并
smallerp.next = NoSmallerXNode.next;
nosmallerq.next = null;
// 返回分隔后的链表头节点
return smallerXNode.next;
}
}
好久没写代码了,开始恢复吧,会陆续刷题。