Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
public ListNode partition(ListNode head, int x) {
if (head == null) return null;
List<Integer> lList = new ArrayList<>();
List<Integer> rList = new ArrayList<>();
while (true) {
if (head.val < x) {
lList.add(head.val);
} else {
rList.add(head.val);
}
if (head.next == null) {
break;
}
head = head.next;
}
lList.addAll(rList);
ListNode index = new ListNode(0);
ListNode result = new ListNode(0);
for (int i = 0; i < lList.size(); i++) {
index.next = new ListNode(lList.get(i));
index = index.next;
if (i == 0) {
result = index;
}
}
return result;
}