/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode itr = head;
ListNode lessDummy = new ListNode(0), greaterEqualDummy = new ListNode(0);
ListNode lessItr = lessDummy, greaterEqualItr = greaterEqualDummy;
for( ; head != null; head = head.next) {
if(head.val < x) {
lessItr.next = head;
lessItr = head;
} else {
greaterEqualItr.next = head;
greaterEqualItr = head;
}
}
lessItr.next = greaterEqualDummy.next;
greaterEqualItr.next = null;
return lessDummy.next;
}
}
Time: O(n)
Space: O(1)