[LeetCode] 86. Partition List Java

题目:

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的点之前,分别需要保持保持两部分中点的相对位置不变。可以分别得到大于等于x的链表和小于x的链表,然后把两个链表组合起来就是需要的结果。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        
        ListNode list1=new ListNode(0);
        ListNode list2=new ListNode(0);
        ListNode p1=list1;
        ListNode p2=list2;
        
        ListNode start=head;
        while(start!=null){
            int value=start.val;
            if(value<x){
                p1.next = start;
                p1=p1.next;
                // list1.next=null;
            }else{
                p2.next = start;
                p2=p2.next;
            }
            start=start.next;
        }
        p2.next=null;

        p1.next=list2.next;
        
        return list1.next;
    }
}

 

posted @ 2017-12-16 10:28  荒野第一快递员  阅读(303)  评论(0编辑  收藏  举报