zoukankan      html  css  js  c++  java
  • [Algo] 42. Partition Linked List

    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

    /**
     * class ListNode {
     *   public int value;
     *   public ListNode next;
     *   public ListNode(int value) {
     *     this.value = value;
     *     next = null;
     *   }
     * }
     */
    public class Solution {
      public ListNode partition(ListNode head, int target) {
        // Write your solution here
        // need to use seperate dummy head node for small and large
        ListNode small = new ListNode(0);
        ListNode large = new ListNode(0);
    
        ListNode smallHead = small;
        ListNode largeHead = large;
        while (head != null) {
          if (head.value < target) {
            small.next = head;
            small = small.next;
          } else {
            large.next = head;
            large = large.next;
          }
          head = head.next;
        }
        small.next = largeHead.next;
        large.next = null;
        return smallHead.next;
      }
    }
  • 相关阅读:
    JavaSE_11_File类、递归
    JavaSE_10_IO流
    leyou_07_对数据的操作
    JavaSE_09_Map
    JavaSE_08_Collections常用功能
    java 22
    java 22
    java 22
    java 22
    java 22
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12776609.html
Copyright © 2011-2022 走看看