please tell code with an optimal approach.
i have passed all test cases but just curious to know an optimized solution.
Reverse k elements of a linked list
public void reverse(int k) throws Exception {
// Write your code here
Main prev = null;
while (this.size != 0) {
Main curr = new Main();
for (int i = 1; i <= k; i++) {
curr.addFirst(this.removeFirst());
}
if (prev == null) {
prev = curr;
} else {
prev.tail.next = curr.head;
prev.tail = curr.tail;
prev.size += curr.size;
}
}
this.head = prev.head;
this.tail = prev.tail;
this.size = prev.size;
}
you can see this