【算法一则】分隔链表

题目

给你一个链表的头节点 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 链表
相关推荐
电院大学僧31 分钟前
初学python的我开始Leetcode题10-2
python·算法·leetcode
码破苍穹ovo2 小时前
二分查找----1.搜索插入位置
数据结构·算法
烨然若神人~3 小时前
算法第38天|322.零钱兑换\139. 单词拆分
算法
sukalot3 小时前
window显示驱动开发—输出合并器阶段
驱动开发·算法
fei_sun3 小时前
【编译原理】语句的翻译
算法
Xの哲學4 小时前
hostapd 驱动注册机制深度分析
linux·网络·算法·wireless
liujing102329294 小时前
Day05_数据结构大项目作业20250620
数据结构
int型码农4 小时前
数据结构第八章(六)-置换选择排序和最佳归并树
java·c语言·数据结构·算法·排序算法
@我漫长的孤独流浪5 小时前
数据结构----排序(3)
数据结构·c++·算法
依然易冷5 小时前
【APR-自动代码修复】论文分享:PyTy
算法