我正在参与掘金新人创作活动,一起开启写作之路。
算法与数据结构-分隔链表
LeetCode:地址
题目要求
给你一个链表的头节点 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]
提示:
- 链表中节点的数目在范围
[0, 200]
内 -100 <= Node.val <= 100
-200 <= x <= 200
思路
遍历一次链表,将 >=
放到 large
链表里面,将 <
的分别放到 small
链表里面,最后组装 large
、small
即可
代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} x
* @return {ListNode}
*/
var partition = function(head, x) {
let samll = new ListNode(0);
let large = new ListNode(0);
let min = samll;
let max = large;
while(head) {
let temp = head.next;
if(head.val >= x) {
max.next = head;
max.next.next = null;
max = max.next;
} else {
min.next = head;
min.next.next = null;
min = min.next;
}
head = temp;
}
min.next = large.next;
return samll.next;
};