My Java Solution. Hope it may helps. Avoid the loop.


  • 1
    L

    The tricky part for this is to avoid the loop between the two lists.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode partition(ListNode head, int x) {
            ListNode p1 = new ListNode(0);
            ListNode p2 =new ListNode(0);
            ListNode p1head = p1;
            ListNode p2head = p2;
             
            ListNode p = head;
            
            while(p!= null){
                if (p.val <x){
                    p1.next = p;
                    p1 = p1.next;
                }else{
                    p2.next = p;
                    p2 = p2.next;
                }
                p = p.next;
            }
    
            p2.next = null;
            p1.next =p2head.next;
            return p1head.next;
        }
    }
    

Log in to reply
 

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