Leetcode86_分隔链表

1.leetcode原题链接:. - 力扣(LeetCode)

2.题目描述

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

3.实现方法

  思路:定义两个链表small和big,遍历链表,小于x值放到small链表中,大于等于x值放到big链表中,最后small的尾节点连接big的头节点

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small =new ListNode(-1);
        ListNode big=new ListNode(-1);
        ListNode sHead=small;
        ListNode bHead=big;

        while(head != null){
            if(head.val < x){
                small.next=head;
                small=small.next;
            }else{
                big.next=head;
                big=big.next;
            }
            head=head.next;
        }
        big.next=null;
        small.next=bHead.next;
        return sHead.next;
    }
}

相关推荐

  1. 【力扣】86. 分隔

    2024-04-22 20:46:04       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-22 20:46:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-22 20:46:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-22 20:46:04       82 阅读
  4. Python语言-面向对象

    2024-04-22 20:46:04       91 阅读

热门阅读

  1. ERESOLVE overriding peer dependency npm install错误

    2024-04-22 20:46:04       36 阅读
  2. ChatGPT改写:论文写作新时代

    2024-04-22 20:46:04       40 阅读
  3. LeetCode49字母异位词分组

    2024-04-22 20:46:04       32 阅读
  4. 【JVM】JVM的垃圾回收机制与垃圾回收器的选择

    2024-04-22 20:46:04       34 阅读
  5. 从安装系统到部署datax

    2024-04-22 20:46:04       40 阅读
  6. CS32 C++ programming

    2024-04-22 20:46:04       32 阅读
  7. LeetCode-94-二叉树的中序遍历

    2024-04-22 20:46:04       27 阅读
  8. springboot接口提高查询速度方法

    2024-04-22 20:46:04       39 阅读
  9. 分治法构建Gray码问题

    2024-04-22 20:46:04       34 阅读
  10. 深入理解与运用Vue 2中的插槽(Slots)

    2024-04-22 20:46:04       35 阅读
  11. 测试testing1

    2024-04-22 20:46:04       29 阅读