【算法一则】分隔链表

题目

给你一个链表的头节点 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 链表
相关推荐
pystraf2 分钟前
UOJ 228 基础数据结构练习题 Solution
数据结构·c++·算法·线段树
海底火旺11 分钟前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
祁同伟.21 分钟前
【数据结构 · 初阶】- 堆的实现
c语言·数据结构
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂2 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论