zoukankan      html  css  js  c++  java
  • [LintCode] Partition List

     Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

    You should preserve the original relative order of the nodes in each of the two partitions.

    Example

    Given 1->4->3->2->5->2->null and x = 3,
    return 1->2->2->4->3->5->null.

    Algorithm:

    1. create two dummy nodes for two possible sublists, one for all nodes < x, one for all nodes >= x;

    2. iterate the input list, add nodes to either sublist accordingly and remove the existing link;

    3. concat the two sublists.

    Runtime: O(n), Space: O(1)

     1 /**
     2  * Definition for ListNode.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int val) {
     7  *         this.val = val;
     8  *         this.next = null;
     9  *     }
    10  * }
    11  */
    12 
    13 
    14 public class Solution {
    15     /*
    16      * @param head: The first node of linked list
    17      * @param x: An integer
    18      * @return: A ListNode
    19      */
    20     public ListNode partition(ListNode head, int x) {   
    21         if(head == null || head.next == null) {
    22             return head;
    23         }
    24         ListNode dummyNode1 = new ListNode(0);
    25         ListNode dummyNode2 = new ListNode(0);
    26         ListNode endNode1 = dummyNode1, endNode2 = dummyNode2, temp = null;
    27         ListNode curr = head;
    28         while(curr != null) {
    29             temp = curr.next;
    30             if(curr.val < x) {
    31                 endNode1.next = curr;
    32                 endNode1 = curr;
    33                 endNode1.next = null;
    34             }
    35             else {
    36                 endNode2.next = curr;
    37                 endNode2 = curr;
    38                 endNode2.next = null;
    39             }
    40             curr = temp;
    41         }
    42         if(endNode1 == null) {
    43             return dummyNode2.next;
    44         }
    45         endNode1.next = dummyNode2.next;
    46         return dummyNode1.next;
    47     }
    48 }

    Related Problems

    Partition Array

  • 相关阅读:
    图像轮廓最大内接矩形的求法
    python利用sift和surf进行图像配准
    Faster Rcnn随笔
    opencv利用svm训练
    灰度图片均衡化源码
    彩色直方图(源码)
    Tensorflow内存暴涨问题
    C++写入txt
    C++生成dll以及调用(函数)和类
    列表元素的几种统计方法总结(嵌套列表)
  • 原文地址:https://www.cnblogs.com/lz87/p/7498012.html
Copyright © 2011-2022 走看看