Java - Simple Solution


  • 0
    T

    Simply maintain two separate linked lists. First for all values less than x and second for others. Construct the 2 linked lists while traversing the given linked list and just connect the two together at the end and return the start of the first linked list.

    Very easy.

    /**
     * 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) {
            if(head == null || head.next == null) return head;
            ListNode curr1 = new ListNode(0);
            ListNode a=curr1;
            ListNode curr2 = new ListNode(0);
            ListNode b = curr2;
            ListNode p = head;
            while(p!=null){
                if(p.val < x){
                    a.next = new ListNode(p.val);
                    a = a.next;
                }else{
                    b.next = new ListNode(p.val);
                    b = b.next;
                }
                p=p.next;
            }
            a.next = curr2.next;
            return curr1.next;
        }
    }
    

Log in to reply
 

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