[路飞]_LeetCode题86分隔链表

195 阅读2分钟

题目描述

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

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/pa… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

以x为界,分离出小于x的所有节点串联成新链表和大于等于x的所有节点串联成新链表,依题意,小于x的节点新链表链接大的新链表即可。

image.png

题解代码

 * 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 bigRet = new ListNode(),smallRet = new ListNode();

  //分别用指针指向各自头结点
  let small = smallRet,big = bigRet,cur = head;

  //遍历链表
  for(let cur = head,next; cur; cur = next){
    
    next = cur.next;//next指向cur下一个节点
    cur.next = null;//jiangcur的节点断开链接,形成单独的节点
    
    if(cur.val < x){
      small.next = cur;//cur的值满足小于x的条件则向small链表拼接
      small = cur;//移动small
    }else{
      big.next = cur;//cur的值满足不小于x的条件则向big链表拼接
      big = cur;//移动big
    }
  }
  small.next = bigRet.next;//small链接big链表
  
  //此时按照题目排列顺序,small链表的的头结点smallRet.next返回即可
  return smallRet.next;
};