Easy Java solution using few pointers


#1

/**

  • Definition for singly-linked list.

  • class ListNode {

  • public int val;
    
  • public ListNode next;
    
  • ListNode(int x) { val = x; next = null; }
    
  • }
    */
    public class Solution {
    public ListNode partition(ListNode A, int B) {

     ListNode dummy = new ListNode(0);
     dummy.next = A;
     ListNode prev = dummy;
     
     ListNode temp = A;
    
     ListNode ptr = A;
     
     while( temp!=null){
         
         if(prev.next == temp &&temp.val < B){
             ptr = temp;
             temp = temp.next;
             prev = prev.next;
         }
         
         else if(temp.val < B){
             
             ptr.next = temp.next;
             temp.next = prev.next;
             prev.next = temp;
             temp = ptr.next;
             prev = prev.next;
          
             
         }
         
         else if(temp.val>=B){
         ptr = temp;
         temp = temp.next;
         }
         
     }
     return dummy.next;
    

    }

}