[leedcode 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.

 

/**

 * 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) {

        //本题第一种解法非常简单,建立两个两表,一个代表小于x的,两一个代表大于等于x的。

        //遍历链表,如果节点值小于x,则添加在minList的尾部,并更新minLIst

        //需要注意的是:最后需要将maxList的尾节点置空,防止形成环形链表

        if(head==null) return head;

        /*ListNode minList=new ListNode(-1);

        ListNode minHead=minList;

        ListNode maxList=new ListNode(-1);

        ListNode maxHead=maxList;

        while(head!=null){

            if(head.val>=x){

                maxList.next=head;

                maxList=head;

            }else{

                minList.next=head;

                minList=head;

            }

            head=head.next;

            

        }

        maxList.next=null;

        minList.next=maxHead.next;

        return minHead.next;*/

        

        /*

        这个解法不满足要求,会破坏原来的顺序

        ListNode i=head;

        ListNode j=head;

        while(j!=null){

            if(j.val<x){

                swap(i,j);

                i=i.next;

                

            }

                j=j.next;

            

        }

        return head;*/

        //本题第三种解法,是原地变换。

        //首先需要找到第一个大于或等于x的节点并赋值给p2,同时p1指向它的前置节点

        //然后从p2到链表尾部进行遍历,当p2下一节点的值小于x时,需要把p2的next节点插入到

        //p1的next

        //p1维持的是小于x的尾节点,画图会更清晰

        

         ListNode newHead=new ListNode(-1);

         newHead.next=head;

         ListNode p1=newHead;

         ListNode p2=head;

         ListNode p1_rear=head;

         while(p2!=null&&p2.val<x){///////

           p1=p1.next;

           p2=p2.next;

         }

        while(p2!=null&&p2.next!=null){

            if(p2.next.val<x){

                p1_rear=p1.next;

                p1.next=p2.next;

                p2.next=p2.next.next;

                p1.next.next=p1_rear;

                p1=p1.next;

            

           }else{

                p2=p2.next;

            }

        }

        return newHead.next;

    }

    /*public void swap(ListNode i,ListNode j){

        int temp=i.val;

        i.val=j.val;

        j.val=temp;

    }*/

    

}

 

你可能感兴趣的:(partition)