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;
      }
    }
  • 相关阅读:
    异常及throw、与throws的介绍
    js数组
    正则表达式
    Date对象及toString方法
    js中函数与对象的使用
    js细节
    JavaScript介绍
    浮动、定位
    css背景样式
    盒子模型
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12776609.html
Copyright © 2011-2022 走看看