86.Partition List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode small = dummy1;
        ListNode big = dummy2;
        while(head != null){
            if(head.val < x){
                small.next = head;
                small = small.next;
            }
            else{
                big.next = head;
                big = big.next;
            }
            head = head.next;
        }
        small.next = dummy2.next;
        big.next = null;
        return dummy1.next;
    }
}

results matching ""

    No results matching ""