Simple Java Solution


  • 0
    Z
     
    public class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head == null || head.next == null){
                return head;
            }
    
            ListNode smallHead = new ListNode(-1);
            ListNode smallTail = smallHead;
            ListNode bigHead = new ListNode(-1);
            ListNode bigTail = bigHead;
    
            while (head != null){
                if(head.val < x){
                    smallTail.next = head;
                    smallTail = head;
                }else {
                    bigTail.next = head;
                    bigTail = head;
                }
                head = head.next;
            }
            smallTail.next = null;
            bigTail.next = null;
    
            if(smallHead.next == null){
                return bigHead.next;
            }
            if(bigHead.next == null){
                return smallHead.next;
            }
    
            smallTail.next = bigHead.next;
    
            return smallHead.next;
        }
    }
    

Log in to reply
 

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