Java 1ms solution


  • 0
    G
    /**
     * 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 beforeXStart = null;
        	ListNode beforeXEnd = null;
        	ListNode afterXStart = null;
        	ListNode afterXEnd = null;
        	
        	ListNode curr = head;
        	while(curr != null) {
        		if (curr.val < x) {
        			if (beforeXStart == null) {
        				beforeXStart = curr;
        				beforeXEnd = curr;
        			} else {
            			beforeXEnd.next = curr;    			
            			beforeXEnd = beforeXEnd.next;    				
        			}
        		} else {
        			if (afterXStart == null) {
        				afterXStart = curr;
        				afterXEnd = curr;
        			} else {
            			afterXEnd.next = curr;    			
            			afterXEnd = afterXEnd.next;    				
        			}
        		}    		    		
        		curr = curr.next;
        	}
        	if (beforeXEnd == null) {
        		return head;
        	}
        	beforeXEnd.next = afterXStart;
        	if (afterXEnd != null) {
        	    afterXEnd.next = null;
        	}
        	return beforeXStart;
        }
    }
    

Log in to reply
 

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