[路飞] 12——leetcode-[86] 分隔链表

135 阅读1分钟

86. 分隔链表

给你一个链表的头节点 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]

提示:

  • 链表中节点的数目在范围 [0, 200] 内
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

代码实现:

/*
 * @lc app=leetcode.cn id=86 lang=javascript
 *
 * [86] 分隔链表
 */

// @lc code=start
/**
 * 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) return null;
  // 创建两个链表,一个链表存储比X小的元素,一个链表存储比X大的元素
  let big = new ListNode(), small = new ListNode();
  // 为两个链表定语两个指针
  let bigNode = big, smallNode = small;
  // 定义原链表的头指针,然后进行比较,连接到对应的链表,然后进行移动
  for (let cur = head, next; cur; cur = next) {
    next = cur.next;
    cur.next = null;
    if (cur.val < x) {
      smallNode.next = cur;
      smallNode = cur;
    } else {
      bigNode.next = cur;
      bigNode = cur;
    }
  }
  // 将两个链表拼接在了一起
  smallNode.next = big.next;
  return small.next;
};
// @lc code=end