分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode min = new ListNode(0);
        ListNode max = new ListNode(0);
        ListNode tmin = min;
        ListNode tmax = max;
        while (head != null) {
            if (head.val >= x) {
                max.next = head;
                max = head;
            }else if (head.val < x) {
                min.next = head;
                min = head;
            }
            head = head.next;
        }
        min.next = null;
        max.next = null;
        
        min.next = tmax.next;
        return tmin.next;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 题目地址:https://leetcode-cn.com/problems/partition-list/desc...
    monkey01阅读 231评论 0 0
  • 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你应当保留两...
    vbuer阅读 268评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,073评论 19 139
  • 加油。
    星辰x阅读 233评论 0 0
  • 国内npm镜像 淘宝npm镜像 搜索地址:http://npm.taobao.org/registry地址:htt...
    wuway阅读 10,223评论 0 0

友情链接更多精彩内容