LeetCode第86题:分隔链表

题干

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

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

实例1

img

输入: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
喜欢就支持一下吧
点赞0 分享