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

leetcode 86. Partition List

时间:2016-07-28 14:22:08      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

 

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 

题意:

给出一个链表和一个数字x,将链表分区,小于x的都放在大于等于x的前面,而且要保持每个分区内各结点的相对位置没有发生变化。

比如原链表中,4在3的前面,3在5的前面,分区后依然要保持这个相对位置。

过程:

(1)新建两个链表,一个first,一个second,

一个用来记录链表中所有小于x的结点,一个用于记录链表中所有大于等于x的结点。

(2)遍历原链表。

(3)最后将两个链表连接起来作为结果返回。

 

public class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head == null) return null;
        
        ListNode firstDummy = new ListNode(0);
        ListNode secondDummy = new ListNode(0);
        ListNode first = firstDummy, second = secondDummy;
        
        while(head != null){
            if(head.val < x){
                first.next = head;
                first = head;
            }else{
                second.next = head;
                second = head;
            }
            head = head.next;
        }
        
        first.next = secondDummy.next;
        second.next = null;
        return firstDummy.next;
    }
}

 

leetcode 86. Partition List

标签:

原文地址:http://www.cnblogs.com/iwangzheng/p/5714433.html

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