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

  • 相关阅读:
    MVC应用程序使用Entity Framework
    @Styles的nameSpace是什么
    创建第一个MVC应用程序
    计算DataTable某列的值(SUM)
    DropDownList 控件的SelectedIndexChanged事件触发不了
    在类中使用Response.Redirect()方法
    控制某个panel的display样式
    获取指定日期下个月份的第一天
    字符串如何还原为中文
    判断字符串中包含3个连续(升、降)或相同的数字
  • 原文地址:https://www.cnblogs.com/lz87/p/7498012.html
Copyright © 2011-2022 走看看