import java.util.*;
public class Solution {
    public ListNode partition (ListNode head, int x) {
        if(head==null)
            return null;

        ListNode small = new ListNode(0);
        ListNode p = small;

        ListNode large = new ListNode(0);
        ListNode q = large;

        while(head != null){
            if(head.val<x){
                p.next = head;
                p = p.next;
                head = head.next;
            }else{
                q.next = head;
                q = q.next;
                head = head.next;
            }
        }

        q.next = null;
        p.next = large.next;

        return small.next;
    }
}