Partition List

description:

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.

thoughts:
我们创建两个链表,第一个链表用来记录小于x的listnode,另一个链表用来记录大于等于x的listnode,然后将前一个链表的尾指针之下第二个两遍,实现两个链表的merge。

以下是java代码:

package middle;

class ListNode{
    int val;
    ListNode next;
    ListNode(int x){
        val = x;
    }
}

public class PartitionList {
    public ListNode partition(ListNode head, int x){
        ListNode dumy1 = new ListNode(0);
        ListNode dumy2 = new ListNode(0);
        ListNode cur1 = dumy1;
        ListNode cur2 = dumy2;
        while(head!=null){
            if(head.val < x){
                cur1.next = head;
                cur1 = cur1.next;
            }else{
                cur2.next = head;
                cur2 = cur2.next;
            }
            head = head.next;
        }
        cur2.next = null;
        cur1.next = dumy2.next;
        return dumy1.next;
    }
    public static void main(String[] args){
        PartitionList p = new PartitionList();
        int x = 5;
        ListNode head = new ListNode(0);
        ListNode tail = head;
        for(int i = 0;i<5;i++){
            ListNode tempNode = new ListNode(i);
            head.next = tempNode;
            head = head.next;
        }
        head.next = null;
        p.partition(tail, x);
        while(tail != null){
            System.out.println(tail.val);
            tail = tail.next;
        }
    }
    
}

 

posted @ 2017-09-18 11:14  whatyouknow123  阅读(117)  评论(0编辑  收藏  举报