zoukankan      html  css  js  c++  java
  • LC.86. Partition List

    https://leetcode.com/problems/partition-list/description/


    Given a linked list and a target value T, partition it such that all nodes less than T are listed before the nodes larger than or equal to target value T. The original relative order of the nodes in each of the two partitions should be preserved.

    Examples

      • L = 2 -> 4 -> 3 -> 5 -> 1 -> null, T = 3, is partitioned to 2 -> 1 -> 4 -> 3 -> 5 -> null

     1 public ListNode partition(ListNode head, int target) {
     2     // Write your solution here
     3     if(head == null || head.next == null) return head ; 
     4     ListNode smallHead = new ListNode(0),
     5                      smallCurr =  smallHead,
     6              largeHead = new ListNode(0), 
     7                      largeCurr = largeHead, 
     8                      curr = head ; 
     9     //no need to keep head
    10     while(curr != null){
    11             if(curr.value<target){
    12             smallCurr.next = curr ; 
    13           smallCurr = smallCurr.next ; 
    14         } else{
    15             largeCurr.next = curr ; 
    16           largeCurr = largeCurr.next ; 
    17         }
    18           curr = curr.next; 
    19     }
    20     //this is super important! otherwise circle!
    21     largeCurr.next = null ; 
    22     //用dummy 的好处,不用担心 small 里到底有没有值
    23     smallCurr.next = largeHead.next ; 
    24     return smallHead.next ; 
    25   }
  • 相关阅读:
    vs c++配置opencv(1)
    vs2013搭建团队版本控制 TFS、SVN
    robomongo
    Node log4js
    node.async.auto
    p2.js物理引擎学习
    pomelo
    Node.mongoose
    Node.Buffer
    Node安装及搭建简单HTTP服务器
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8460673.html
Copyright © 2011-2022 走看看