Java recursive solution


  • 0
    M
    public ListNode partition(ListNode head, int x) {
    	if(head == null) return null;
    	else if(head.next == null)
    		return head;
    	ListNode n = partition(head.next, x),
    			p = head;
    	head.next = n;
    	boolean isHead = true;
    	if(p.val >= x){
    		ListNode prev = p;
    		while((p.next != null && p.next.val < x)){
    			ListNode q = p.next;
    			p.next = q.next;
    			q.next = p;
    			if(isHead){
    				head = q;
    				prev = q;
    				isHead = false;
    			}else {
    				prev.next = q;
    				prev = prev.next;
    			}
    
    		}
    	}
    
    	return head;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.