leetcode 86. Partition List

 

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

 

posted @ 2016-07-28 13:07  冰凌花花~  阅读(126)  评论(0编辑  收藏  举报