[路飞]_leetcode 86.分隔链表

278 阅读1分钟

题目简述

leetcode 86.分隔链表

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

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

示例

示例1:

image.png

输入: 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

解题思路

  1. 先判断head是否为空,或只有一个节点;
  2. 创建samll和large链表
  3. 比较每个节点值与x的大小;
  • 如果nodeval < x, samll -> node;
  • 否则large -> node;
  1. samll链表的尾节点 指向 large链表头节点(->null)

javascript实现

/**
 * 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) {
    if(head == null || head.next == null) return head;
    let small = new ListNode(0), large = new ListNode(0);
    let smHead = small, lgHead = large;
    while(head) {
        if(head.val < x) {
            small.next = head;
            small = small.next;
        }else {
            large.next = head;
            large = large.next;
        }
        head = head.next;
    }
    large.next = null;
    small.next = lgHead.next;
    return smHead.next;
};

视频:bili