Java 1ms simple solution


  • 0
    public ListNode partition(ListNode head, int x) {
        ListNode smallhead = new ListNode(0); //2 dummy heads
        ListNode bighead = new ListNode(0);
        ListNode small = smallhead; //2 iterators
        ListNode big = bighead;
        while(head!=null){
            ListNode temp = new ListNode(head.val);
            if(head.val<x){
                small.next = temp;
                small = small.next;
            }
            else{
                big.next = temp;
                big = big.next;
            }
            head = head.next;
        }
        small.next = bighead.next;//connect 2 lists
        return smallhead.next;
    }

Log in to reply
 

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