首页 > 其他 > 详细

[Algo] 42. Partition Linked List

时间:2020-04-26 09:35:03      阅读:49      评论:0      收藏:0      [点我收藏+]

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;
  }
}

 

[Algo] 42. Partition Linked List

原文:https://www.cnblogs.com/xuanlu/p/12776609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!