[路飞_js算法:分割链表]

156 阅读1分钟

分割链表

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

你不需要 保留 每个分区中各节点的初始相对位置。(by leetcode 面试题 02.04)

示例 1:

img

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]

思路: 设置两条链表,分别设置虚拟头结点,然后小的放在链表1中,大的放在链表2中,链接两条链表的头尾,返回链表1的虚拟头下一个节点。

/**
 * 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) {
    if(head==null)return head;
    let vir1=new ListNode(0);
    let temp1=vir1;
    let vir2=new ListNode(0);
    let temp2=vir2;
    while(head!==null){
        if(head.val<x){
            vir1.next=head;
            vir1=vir1.next
        }else{
            vir2.next=head;
            vir2=vir2.next
        }
        head=head.next
    }
    vir2.next=null;
    vir1.next=temp2.next;
    return temp1.next
};