【算法一则】分隔链表

题目

给你一个链表的头节点 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 链表
相关推荐
拾零吖21 分钟前
枚举算法-day1
数据结构·算法·leetcode
Chandler2435 分钟前
Redis:List 类型 内部实现、编码、命令及应用场景
数据结构·数据库·redis·缓存·list
BingLin-Liu1 小时前
蓝桥杯备考:图论之拓扑排序
算法·图论
哦吼!2 小时前
算法基础——模拟
算法
CYRUS_STUDIO4 小时前
Android 中实现一个自定义的 AES 算法
android·算法·逆向
ElseWhereR9 小时前
机器人能否回到原点 - 简单
c++·算法·leetcode
一只自律的鸡9 小时前
【黑皮书】 AVL树
数据结构
my_realmy9 小时前
蓝桥杯真题_小蓝和小桥的讨论
java·python·算法·职场和发展·蓝桥杯·intellij-idea
泛舟起晶浪9 小时前
海底高铁--差分
数据结构·c++·算法
带娃的IT创业者10 小时前
《Python实战进阶》No37: 强化学习入门:Q-Learning 与 DQN-加餐版1 Q-Learning算法可视化
python·算法·pygame