[路飞]_leetcode_面试题 02.04. 分割链表

86 阅读1分钟

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

你不需要 保留 每个分区中各节点的初始相对位置。

解题思路

这一题可以用双链表来记录 小于 x 的节点和大于等于 x 的节点, 然后两个链表首位相接成一个链表

代码

var partition = function(head, x) {
    let samllHair = new ListNode(-1, null), small = samllHair;
    let largeHair = new ListNode(-1, null), large = largeHair;

    while (head) {
        if (head.val < x) {
            samllHair.next = head;
            samllHair = samllHair.next
        } else {
            largeHair.next = head;
            largeHair = largeHair.next;
        }
        head = head.next;
    }

    largeHair.next = null
    samllHair.next = large.next

    return small.next;
};