题干
给你一个链表的头节点 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]
复制代码
解法:合成链表
我们定义两个链表分别为目标数的左边和右边。然后进行一次循环判断,向两个链表中加加节点即可。最后再将两个链表连接形成我们的结果链表:
代码实现:
/**
* 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 left = new ListNode(-1)
let right = new ListNode(-1)
let currentLeft = left;
let currentRight = right;
while (head != null) {
if (head.val >= x) {
let node1 = new ListNode(head.val)
currentRight.next = node1
currentRight = currentRight.next;
} else {
let node2 = new ListNode(head.val)
currentLeft.next = node2
currentLeft = currentLeft.next;
}
head = head.next
}
currentLeft.next=right.next;
return left.next
};
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END






















![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)