Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place.
Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue.
Input: stack =[1,2,3,4,5]Output: [1,5,2,4,3]Explanation: We interleave first and last element first -1,5, then we interleave 2nd and 2nd last element,2,4 and then finally middle element 3.
publicclassInterleaveStack {
publicstaticvoidinterleaveStack(Stack<Integer> stack) {
Queue<Integer> queue =new LinkedList<>();
int n = stack.size();
int halfSize = n / 2;
// Step 1: Move all elements from stack to queuewhile (!stack.isEmpty()) {
queue.add(stack.pop());
}
// Step 2: Push first half elements back to stackfor (int i = 0; i < halfSize; i++) {
stack.push(queue.remove());
}
// Step 3: Queue the remaining elements to the end of the queuewhile (queue.size() > halfSize) {
queue.add(queue.remove());
}
// Step 4: Interleave elementsfor (int i = 0; i < halfSize; i++) {
queue.add(stack.pop()); // Move from stack to queue queue.add(queue.remove()); // Move front of queue to back }
// Push everything back to stackwhile (!queue.isEmpty()) {
stack.push(queue.remove());
}
// Reverse the stack to maintain original order on interleaved result reverseStack(stack);
}
privatestaticvoidreverseStack(Stack<Integer> stack) {
Queue<Integer> queue =new LinkedList<>();
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
while (!queue.isEmpty()) {
stack.push(queue.remove());
}
}
}
definterleave_stack(stack):
queue = deque()
n = len(stack)
half_size = n //2# Step 1: Move all elements from stack to queuewhile stack:
queue.append(stack.pop())
# Step 2: Push first half elements back to stackfor _ in range(half_size):
stack.append(queue.popleft())
# Step 3: Queue the remaining elements to the end of the queuewhile queue:
queue.append(queue.popleft())
# Step 4: Interleavefor _ in range(half_size):
stack.append(queue.popleft())
queue.append(stack.pop())
while queue:
stack.append(queue.popleft())
return stack