【算法一则】分隔链表

题目

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

ListNode

java 复制代码
public class ListNode {
   int val;
   ListNode next;
   public ListNode() {
   }
  ListNode(int x) {
       val = x;
       next = null;
   }
   ListNode(int x, ListNode next) {
       val = x;
       this.next = next;
   }
}

题解

java 复制代码
package algorithm.link;

import org.junit.Test;

/**
 * Partition
 *
 * @author allens
 * @date 2024/4/15
 */
public class Partition {


    /**
     * partition
     *
     * @param head
     * @param x
     * @return
     */
    public ListNode partition(ListNode head, int x) {
        ListNode left = new ListNode();
        ListNode right = new ListNode();

        ListNode leftHead = left;
        ListNode rightHead = right;

        while (head != null) {
            if (head.val < x) {
                left.next = head;
                left = left.next;
            } else {
                right.next = head;
                right = right.next;
            }
            head = head.next;
        }

        right.next = null;
        left.next = rightHead.next;
        return leftHead.next;
    }

    @Test
    public void testMain () {
        ListNode head = new ListNode(1, new ListNode(4, new ListNode(3, new ListNode(2, new ListNode(5, new ListNode(2))))));
        ListNode partition = partition(head, 3);
        print(partition);
        System.out.println(partition);
    }

    private void print(ListNode partition) {
        while (partition != null) {
            System.out.print(partition.val + " ");
            partition = partition.next;
        }
    }

}
    1. 定义两个链表 left 和 right,分别存储小于 x 和大于等于 x 的节点
    1. 遍历链表,将小于 x 的节点放到 left 链表中,大于等于 x 的节点放到 right 链表中
    1. 将 left 和 right 链表连接起来
    1. 返回 left 链表
相关推荐
故事和你913 分钟前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
qq_4232339015 分钟前
C++与Python混合编程实战
开发语言·c++·算法
TracyCoder12325 分钟前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_7155753427 分钟前
分布式任务调度系统
开发语言·c++·算法
naruto_lnq1 小时前
泛型编程与STL设计思想
开发语言·c++·算法
zxsz_com_cn1 小时前
设备预测性维护算法分类及优劣势分析,选型指南来了
算法·分类·数据挖掘
m0_748708052 小时前
C++中的观察者模式实战
开发语言·c++·算法
然哥依旧2 小时前
【轴承故障诊断】基于融合鱼鹰和柯西变异的麻雀优化算法OCSSA-VMD-CNN-BILSTM轴承诊断研究【西储大学数据】(Matlab代码实现)
算法·支持向量机·matlab·cnn
qq_537562672 小时前
跨语言调用C++接口
开发语言·c++·算法