Java without Dummynodes


  • 0
    M
    public class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head==null) return head;
            ListNode left = null;
            ListNode right = null;
            ListNode curr = head;
            ListNode leftHead = null;
            ListNode rightHead = null;
            while(curr!=null){
                if (curr.val < x){
                    if(left==null) {
                        left = curr;
                        leftHead = curr;
                    }else{left.next = curr;left = left.next;}
                }else{
                    if(right == null){
                        right = curr; rightHead = curr;
                    }else{right.next=curr;right=right.next;}
                    
                }
                curr = curr.next;
            }
            if(leftHead==null) return rightHead;
            if(right!=null) right.next = null;
            left.next = rightHead;
            return leftHead;
        }
    }

Log in to reply
 

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