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;
        }
  • 相关阅读:
    vue-cli3使用cdn引入
    修饰器
    go strconv
    【BZOJ 5125】小Q的书架
    【NOI 2009】诗人小G
    后缀数组
    点分治
    四边形不等式
    【NOIP 2015】Day2 T3 运输计划
    【NOIP 2016】Day1 T2 天天爱跑步
  • 原文地址:https://www.cnblogs.com/twoheads/p/10607133.html
Copyright © 2011-2022 走看看