Java easy to understand solution

  • 1

    Idea is straight forward, scan the original list, move those item larger or equal to x to a new list. After the scan, connect the new list to the tail of original list. Note that although we are conceptually using a new list, we only used O(1) extra space since this is linked list not array.


    public class Solution{
        public ListNode partition(ListNode head, int x) {
            ListNode small = new ListNode(0);
            ListNode large = new ListNode(0);
   = head;
            ListNode scanner = small;
            ListNode tail = large;
            while ( != null) {
                if ( >= x) {
                    tail =;
           = null;
                    scanner =;

    Runtime: 1ms

Log in to reply

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