【算法一则】分隔链表

题目

给你一个链表的头节点 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 链表
相关推荐
✿ ༺ ོIT技术༻11 分钟前
笔试强训:Day6
数据结构·c++·算法
阳洞洞32 分钟前
234. Palindrome Linked List
leetcode·链表
jz_ddk3 小时前
[学习] C语言多维指针探讨(代码示例)
linux·c语言·开发语言·学习·算法
星夜9825 小时前
C++回顾 Day6
开发语言·数据结构·c++·算法
asom228 小时前
LeetCode Hot100(矩阵)
算法·leetcode·矩阵
蒟蒻小袁8 小时前
力扣面试150题--二叉树的右视图
算法·leetcode·面试
一块plus8 小时前
当 Bifrost 与 Hydration 携手:Gigadot 能为 Polkadot DeFi 带来哪些新可能?
算法·架构
进击的小白菜9 小时前
LeetCode 215:数组中的第K个最大元素 - 两种高效解法详解
java·算法·leetcode
写个博客10 小时前
代码随想录算法训练营第五十三天
算法
1白天的黑夜111 小时前
动态规划-152.乘积最大子数组-力扣(LeetCode)
c++·算法·leetcode·动态规划