码迷,mamicode.com
首页 > 其他好文 > 详细

[Algo] 42. Partition Linked List

时间:2020-04-26 09:21:42      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:amp   nal   node   code   get   res   each   relative   HERE   

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

标签:amp   nal   node   code   get   res   each   relative   HERE   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!