Thought my java solution might be helpful for someone


  • 0
    M

    The idea is to traverse the array and create two new arrays , one with value smaller than x and one with value greater than x, and then attach the two new arrays together. Below is the java solution:

        public ListNode partition(ListNode head, int x) {
            
            if (head == null || head.next == null) return head;
           
        	ListNode new_hed1 = new ListNode(0);
        	ListNode new_hed2 = new ListNode(0);
        	
        	ListNode new_hed22 = new ListNode(0);
        	
        	ListNode new_hed11 = new ListNode(0);
       
        	
        	boolean first=false, second=false;
        	
        	for(ListNode p = head; p!=null; p=p.next){
        		if(p.val<x){
        			new_hed1.next = p;
        			new_hed1 = new_hed1.next;
        			if(!first){
        				first=true;
        				new_hed11.next = new_hed1;
        			}
        		}
        		else{
        			new_hed2.next = p;
        			new_hed2 = new_hed2.next;
        			if(!second){
        				second=true;
        				new_hed22.next = new_hed2;
        			}
        		}
        	}
        	new_hed2.next=null;
    
        	
        // 	System.out.println(new_hed22.next.val);
        // 	System.out.println(new_hed11.next.val);
        
            if(!first){
        		return new_hed22.next;
        	}
        	
        	new_hed1.next=new_hed22.next;
    	return new_hed11.next;
        }
        
    
    

Log in to reply
 

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