I came up with the following code while trying to solve the Leetcode partition list problem
Though my solution is accepted, I am not happy with a few of the additional variables which I am creating. In the code below, I would like to avoid creation of tailEnd
and headEnd
variables somehow.
Can you please review the code and suggest a better way to write this code.
public ListNode partition(ListNode head, int x) {
ListNode partitionHead = null;
ListNode partitionTail = null;
ListNode headEnd = null;
ListNode tailEnd = null;
ListNode node = head;
while (node != null) {
if (node.val <x ) {
if (partitionHead == null) {
partitionHead = node;
} else {
headEnd.next = node;
}
headEnd = node;
} else {
if (partitionTail == null) {
partitionTail = node;
} else {
tailEnd.next = node;
}
tailEnd = node;
}
node = node.next;
}
if (tailEnd != null) {
tailEnd.next = null;
}
if (partitionHead == null) {
return partitionTail;
}
headEnd.next = partitionTail;
return partitionHead;
}
while
could be better expressed asfor (ListNode node = head; node != null; node = node.next) {
\$\endgroup\$