Easy Idea of Java Solution


  • 0
    A

    The idea is to move the nodes that have equal or greater value to the end. Remember to mark the end of the original list.

    /**
     * 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 help = new ListNode(0);
            help.next = head;
            ListNode check = help;
            ListNode tail = help;
            int counter = 0;
            
            while(tail.next!=null){
                tail = tail.next;
                counter++;
            }
            //ListNode end = tail;
            
            while(counter>0&&check.next.next!=null ){
                if(check.next.val<x){
                    check = check.next;
                    counter--;
                }
                else{
                    ListNode next = check.next;
                    check.next = check.next.next;
                    tail.next = next;
                    next.next = null;
                    //check = check.next;
                    tail = tail.next;
                    counter--;
                }
            }
            return help.next;
        }
    }
    

Log in to reply
 

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