List partition

Problem: Given a list and a value x, the linked list into two, i.e. all the nodes is smaller than or equal to x is greater than before in the node x, and the relative order of the original node is stored.

Ideas: the use of a pointer to a demarcation point, traverse the list is less than x encountered node is inserted into the cut-off point.

java code:

ListNode partitionLinkedList(ListNode head,int x){
        ListNode curr=head;
        ListNode dummy=null;
        if(curr.val<x){
            dummy=curr;
        }
        while(curr.next!=null){
            if(curr.next.val<x){
                if(dummy==null){
                    ListNode tmp=curr.next;
                    curr.next=curr.next.next;
                    tmp.next=head;
                    dummy=tmp;
                    head=dummy;
                }
                else{
                    ListNode tmp=curr.next;
                    curr.next=curr.next.next;
                    tmp.next=dummy.next;
                    dummy.next=tmp;
                    dummy=tmp;
                }
            }
            else{
                curr=curr.next;
            }
        }
        return head;
    }
Published 18 original articles · won praise 0 · Views 661

Guess you like

Origin blog.csdn.net/qq_42060170/article/details/104302409