美文网首页
86. 分隔链表

86. 分隔链表

作者: 最尾一名 | 来源:发表于2020-03-07 17:38 被阅读0次

原题

https://leetcode-cn.com/problems/partition-list/submissions/

解题思路

用两条链表,一条放值小于 val 的节点,一条放值大于等于 val 的节点
最后合并两条链表

代码

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} x
 * @return {ListNode}
 */
var partition = function(head, x) {
    const dumpy1 = new ListNode(-1), dumpy2 = new ListNode(-1);
    dumpy1.next = head;
    let left = dumpy1, right = dumpy2;
    while (left && left.next) {
        const current = left.next;
        if (current.val >= x) {
            right.next = current;
            right = current;
            left.next = current.next;
            current.next = null;
        } else {
            left = current;
        }
    }
    left.next = dumpy2.next;
    return dumpy1.next;
};

复杂度

  • 时间复杂度 O(N)
  • 空间复杂度 O(1)

相关文章

  • 86. 分隔链表

    86. 分隔链表[https://leetcode-cn.com/problems/partition-list/...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode.cn/problems/partition-list/] 给你...

  • 力扣每日一题:86.分隔链表 创建大小链表与寻找第一个链表头两种

    86.分隔链表[https://leetcode-cn.com/problems/partition-list/s...

  • 86. 分隔链表

    86. 分隔链表 问题 给定一个链表和一个特定值 ,对链表进行分隔,使得所有小于 的节点都在大于或等于的节点之前。...

  • 86. 分隔链表

    双指针法: 直觉我们可以用两个指针pbig 和 psmall 来追踪上述的两个链表。两个指针可以用于分别创建两个链...

  • 86. 分隔链表

    原题 https://leetcode-cn.com/problems/partition-list/submis...

  • 86. 分隔链表

    https://leetcode-cn.com/problems/partition-list/solution/...

  • 86. 分隔链表

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

  • LeetCode 86. 分隔链表

    86. 分隔链表 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点...

  • 每日一题2. 分隔链表

    86. 分隔链表 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点...

网友评论

      本文标题:86. 分隔链表

      本文链接:https://www.haomeiwen.com/subject/ckchdhtx.html