zoukankan      html  css  js  c++  java
  • 【leetcode-86】 分隔链表

    (1过)

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

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

    示例:

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

    思路两个链表拼接
    最初做时犯了个错误,加入新链表后没有与原链表断开,导致超时错误
        public ListNode partition(ListNode head, int x) {
            // 头指针
            ListNode smaller = new ListNode(0);
            ListNode bigger = new ListNode(0);
            ListNode curSmaller = smaller;
            ListNode curBigger = bigger;
            while(head != null) {
                if (head.val < x){
                    curSmaller.next = head;
                    head = head.next;
                    curSmaller = curSmaller.next;
                    // 加入新链表后要与原链表断开
                    curSmaller.next = null;
                } else {
                    curBigger.next = head;
                    head = head.next;
                    curBigger = curBigger.next;
                    curBigger.next = null;
                }
            }
            curSmaller.next = bigger.next;
            return smaller.next;
        }
  • 相关阅读:
    每日日报24
    每日日报23
    每日日报22
    链路层:MAC 地址
    应用层:电子邮件
    应用层:HTTP 协议
    应用层:DNS 域名系统
    运输层:TCP 拥塞控制
    运输层:拥塞控制原理
    JAVA学习日记26-0731
  • 原文地址:https://www.cnblogs.com/twoheads/p/10607133.html
Copyright © 2011-2022 走看看