Given a stack s, remove the middle element of it without using any additional data structure.
Input: s = [10, 20, 30, 40, 50]
Output: s = [10, 20, 40, 50]
Explanation: After deleting the mid which is 30, stack will look like [10, 20, 40, 50].Input: s = [1, 2, 3, 4]
Output: s = [1, 3, 4]
Explanation: The stack has 10 elements (even), there are two mid elements 2 and 3, we delete the first of the two.
Try It Yourself
Note : The output printed by the following codes is reverse of the order as we pop the top elements one by one and print.
Table of Content
Using Vector - O(n) Time and O(n) Space
- Create a vector to store stack elements.
- Pop all elements from the stack and store them in the vector.
- Identify the middle element index: n/2 for even n, ceil(n/2) for odd n (0-based indexing).
- Skip the middle element and push the remaining elements back to the stack in reverse order.
//Driver Code Starts
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
//Driver Code Ends
void deleteMiddle(stack<int>& st) {
vector<int> elements;
// Transfer stack elements to a vector
while (!st.empty()) {
elements.push_back(st.top());
st.pop();
}
// Compute middle index
int midIndex = elements.size() / 2;
// Erase the middle element
elements.erase(elements.begin() + midIndex);
// Push elements back to the stack in reverse order
for (int i = elements.size() - 1; i >= 0; --i) {
st.push(elements[i]);
}
}
//Driver Code Starts
int main() {
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
deleteMiddle(st);
// Print the remaining stack
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
return 0;
}
//Driver Code Ends
//Driver Code Starts
import java.util.Stack;
import java.util.ArrayList;
public class GfG {
//Driver Code Ends
public static void deleteMiddle(Stack<Integer> stack) {
ArrayList<Integer> elements = new ArrayList<>();
// Transfer elements from stack to list
while (!stack.isEmpty()) {
elements.add(stack.pop());
}
// Find and remove the middle element
int midIndex = elements.size() / 2;
elements.remove(midIndex);
// Push elements back into the stack in reverse order
for (int i = elements.size() - 1; i >= 0; i--) {
stack.push(elements.get(i));
}
}
//Driver Code Starts
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
deleteMiddle(stack);
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}
//Driver Code Ends
def delete_middle(stack):
elements = []
# Transfer stack elements to a list
while stack:
elements.append(stack.pop())
mid_index = len(elements) // 2
# Remove the middle element
elements.pop(mid_index)
# Push elements back onto the stack in reverse order
for i in range(len(elements) - 1, -1, -1):
stack.append(elements[i])
#Driver Code Starts
if __name__=="__main__":
stack = [10, 20, 30, 40, 50]
delete_middle(stack)
while stack:
print(stack.pop(), end=' ')
#Driver Code Ends
//Driver Code Starts
using System;
using System.Collections.Generic;
class Program {
//Driver Code Ends
static void DeleteMiddle(Stack<int> st) {
List<int> elements = new List<int>();
// Transfer elements from stack to vector
while (st.Count > 0) {
elements.Add(st.Pop());
}
// Remove the middle element
int midIndex = elements.Count / 2;
elements.RemoveAt(midIndex);
// Push elements back into the stack in correct order
for (int i = elements.Count - 1; i >= 0; i--) {
st.Push(elements[i]);
}
}
//Driver Code Starts
static void Main() {
Stack<int> st = new Stack<int>();
st.Push(10);
st.Push(20);
st.Push(30);
st.Push(40);
st.Push(50);
DeleteMiddle(st);
while (st.Count > 0) {
Console.Write(st.Pop() + " ");
}
}
}
//Driver Code Ends
function deleteMiddle(stack) {
const elements = [];
// Transfer elements from stack to vector
while (stack.length > 0) {
elements.push(stack.pop());
}
// Remove the middle element
const midIndex = Math.floor(elements.length / 2);
elements.splice(midIndex, 1);
// Push elements back into the stack in correct order
for (let i = elements.length - 1; i >= 0; i--) {
stack.push(elements[i]);
}
}
//Driver Code Starts
// Driver code
const stack = [];
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
deleteMiddle(stack);
while (stack.length > 0) {
console.log(stack.pop() + " ");
}
//Driver Code Ends
Output
50 40 20 10
Using Recursion - O(n) Time and O(n) Space
- Store the stack size (n) and initialize a counter (current) to track popped elements.
- Recursively, Pop an element and increment current and If current == n/2, pop the middle element and stop recursion. Otherwise, continue recursion.
- Push back the popped element after the recursive call.
//Driver Code Starts
#include <iostream>
#include <stack>
using namespace std;
//Driver Code Ends
void deleteMid_util(stack<int>& st, int sizeOfStack, int current)
{
// Remove middle element
if (current == sizeOfStack / 2) {
st.pop();
return;
}
// Store top element
int topElement = st.top();
st.pop();
// Recursive call
deleteMid_util(st, sizeOfStack, current + 1);
// Push the element back after recursion
st.push(topElement);
}
void deleteMid(stack<int>& st, int sizeOfStack)
{
deleteMid_util(st, sizeOfStack, 0);
}
//Driver Code Starts
int main()
{
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
deleteMid(st, st.size());
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
return 0;
}
//Driver Code Ends
//Driver Code Starts
import java.util.Stack;
public class GfG {
//Driver Code Ends
public static void deleteMidUtil(Stack<Integer> st, int sizeOfStack, int current) {
// Remove middle element
if (current == sizeOfStack / 2) {
st.pop();
return;
}
// Temporarily remove top element
int topElement = st.pop();
// Recursive call
deleteMidUtil(st, sizeOfStack, current + 1);
// Push back after recursion
st.push(topElement);
}
public static void deleteMid(Stack<Integer> st, int sizeOfStack) {
deleteMidUtil(st, sizeOfStack, 0);
}
//Driver Code Starts
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
deleteMid(st, st.size());
while (!st.isEmpty()) {
System.out.print(st.pop() + " ");
}
}
}
//Driver Code Ends
def deleteMid_util(stack, sizeOfStack, current):
# Remove middle element
if current == sizeOfStack // 2:
stack.pop()
return
# Store top element
topElement = stack.pop()
# Recursive call
deleteMid_util(stack, sizeOfStack, current + 1)
# Push the element back after recursion
stack.append(topElement)
def deleteMid(stack, sizeOfStack):
deleteMid_util(stack, sizeOfStack, 0)
#Driver Code Starts
if __name__=="__main__":
stack = [10, 20, 30, 40, 50]
deleteMid(stack, len(stack))
while stack:
print(stack.pop(), end=' ')
#Driver Code Ends
//Driver Code Starts
using System;
using System.Collections.Generic;
class GfG
{
//Driver Code Ends
static void deleteMid_util(Stack<int> stack, int sizeOfStack, int current)
{
// Remove middle element
if (current == sizeOfStack / 2)
{
stack.Pop();
return;
}
// Store top element
int topElement = stack.Pop();
// Recursive call
deleteMid_util(stack, sizeOfStack, current + 1);
// Push the element back after recursion
stack.Push(topElement);
}
static void deleteMid(Stack<int> stack, int sizeOfStack)
{
deleteMid_util(stack, sizeOfStack, 0);
}
//Driver Code Starts
static void Main()
{
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
deleteMid(stack, stack.Count);
while (stack.Count > 0)
{
Console.Write(stack.Pop() + " ");
}
}
}
//Driver Code Ends
function deleteMidUtil(stack, sizeOfStack, current) {
// Remove middle element
if (current === Math.floor(sizeOfStack / 2)) {
stack.pop();
return;
}
// Store top element
let topElement = stack.pop();
// Recursive call
deleteMidUtil(stack, sizeOfStack, current + 1);
// Push the element back after recursion
stack.push(topElement);
}
function deleteMid(stack, sizeOfStack) {
deleteMidUtil(stack, sizeOfStack, 0);
}
//Driver Code Starts
// Driver code
let stack = [10, 20, 30, 40, 50];
deleteMid(stack, stack.length);
while (stack.length > 0) {
console.log(stack.pop());
}
//Driver Code Ends
Output
50 40 20 10
Using Temporary Stack - O(n) Time and O(n) Space
- Initialize a temporary stack and a counter (count).
- While count < n/2, pop elements from the original stack and push to the temporary stack.
- Pop the middle element from the original stack.
- While the temporary stack is not empty, pop elements from it and push to the original stack.
//Driver Code Starts
#include <iostream>
#include <stack>
using namespace std;
//Driver Code Ends
void deleteMid(stack<int>& st)
{
int n = st.size();
stack<int> tempSt;
int count = 0;
// Move the top half of the elements to a temporary stack
while (count < n / 2) {
tempSt.push(st.top());
st.pop();
count++;
}
// Remove the middle element
st.pop();
// Restore the remaining elements back to the original stack
while (!tempSt.empty()) {
st.push(tempSt.top());
tempSt.pop();
}
}
//Driver Code Starts
int main()
{
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
deleteMid(st);
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
return 0;
}
//Driver Code Ends
//Driver Code Starts
import java.util.Stack;
public class GfG {
//Driver Code Ends
public static void deleteMid(Stack<Integer> st) {
int n = st.size();
Stack<Integer> tempSt = new Stack<>();
int count = 0;
// Move top half to temporary stack
while (count < n / 2) {
tempSt.push(st.pop());
count++;
}
// Remove the middle element
st.pop();
// Restore elements back to original stack
while (!tempSt.isEmpty()) {
st.push(tempSt.pop());
}
}
//Driver Code Starts
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
deleteMid(st);
while (!st.isEmpty()) {
System.out.print(st.pop() + " ");
}
}
}
//Driver Code Ends
def delete_mid(st):
n = len(st)
temp_st = []
count = 0
# Move top half to temporary stack
while count < n // 2:
temp_st.append(st.pop())
count += 1
# Remove the middle element
st.pop()
# Restore elements back to original stack
while temp_st:
st.append(temp_st.pop())
#Driver Code Starts
if __name__=="__main__":
stack = [10, 20, 30, 40, 50]
delete_mid(stack)
while stack:
print(stack.pop(), end=" ")
#Driver Code Ends
//Driver Code Starts
using System;
using System.Collections.Generic;
class GfG
{
//Driver Code Ends
static void DeleteMid(Stack<int> st)
{
int n = st.Count;
Stack<int> tempSt = new Stack<int>();
int count = 0;
// Move top half to temporary stack
while (count < n / 2)
{
tempSt.Push(st.Pop());
count++;
}
// Remove the middle element
st.Pop();
// Restore elements back to original stack
while (tempSt.Count > 0)
{
st.Push(tempSt.Pop());
}
}
//Driver Code Starts
static void Main()
{
Stack<int> st = new Stack<int>();
st.Push(10);
st.Push(20);
st.Push(30);
st.Push(40);
st.Push(50);
DeleteMid(st);
while (st.Count > 0)
{
Console.Write(st.Pop() + " ");
}
}
}
//Driver Code Ends
function deleteMid(stack) {
const n = stack.length;
const tempStack = [];
let count = 0;
// Move top half to temporary stack
while (count < Math.floor(n / 2)) {
tempStack.push(stack.pop());
count++;
}
// Remove the middle element
stack.pop();
// Restore elements back to original stack
while (tempStack.length > 0) {
stack.push(tempStack.pop());
}
}
//Driver Code Starts
// Driver code
let stack = [10, 20, 30, 40, 50];
deleteMid(stack);
while (stack.length > 0) {
console.log(stack.pop());
}
//Driver Code Ends
Output
50 40 20 10