Delete middle element of a stack

20 Jun, 2022
Given a stack with push(), pop(), empty() operations, delete the middle of it without using any additional data structure.
Input  : Stack[] = [1, 2, 3, 4, 5]
Output : Stack[] = [1, 2, 4, 5]

Input  : Stack[] = [1, 2, 3, 4, 5, 6]
Output : Stack[] = [1, 2, 4, 5, 6]
The idea is to use recursive calls. We first remove all items one by one, then we recur. After recursive calls, we push all items back except the middle item.  
C++
Java
Python3
C#
Javascript
// C++ code to delete middle of a stack// without using additional data structure.#include<bits/stdc++.h>using namespace std; // Deletes middle of stack of size// n. Curr is current item number    void deleteMid_util(stack<char>&s, int sizeOfStack, int current)    {        //if current pointer is half of the size of stack then we        //are accessing the middle element of stack.        if(current==sizeOfStack/2)        {            s.pop();            return;        }                 //storing the top element in a variable and popping it.        int x = s.top();        s.pop();        current+=1;         //calling the function recursively.        deleteMid_util(s,sizeOfStack,current);                 //pushing the elements (except middle element) back        //into stack after recursion calls.        s.push(x);    }    void deleteMid(stack<char>&s, int sizeOfStack)    {        deleteMid_util(s,sizeOfStack,0);    }  //Driver function to test above functionsint main(){    stack<char> st;     //push elements into the stack    st.push('1');    st.push('2');    st.push('3');    st.push('4');    st.push('5');    st.push('6');    st.push('7');     deleteMid(st, st.size());     // Printing stack after deletion    // of middle.    while (!st.empty())    {        char p=st.top();        st.pop();        cout << p << " ";    }    return 0;}
// Java code to delete middle of a stack// without using additional data structure.import java.io.*;import java.util.*; public class GFG {     // Deletes middle of stack of size    // n. Curr is current item number    static void deleteMid(Stack<Character> st,                              int n, int curr)    {                 // If stack is empty or all items        // are traversed        if (st.empty() || curr == n)            return;                 // Remove current item        char x = st.pop();                 // Remove other items        deleteMid(st, n, curr+1);                 // Put all items back except middle        if (curr != n/2)            st.push(x);    }         // Driver function to test above functions    public static void main(String args[])    {        Stack<Character> st =                  new Stack<Character>();             // push elements into the stack        st.push('1');        st.push('2');        st.push('3');        st.push('4');        st.push('5');        st.push('6');        st.push('7');             deleteMid(st, st.size(), 0);             // Printing stack after deletion        // of middle.        while (!st.empty())        {            char p=st.pop();            System.out.print(p + " ");        }    }} // This code is contributed by// Manish Shaw (manishshaw1)
# Python3 code to delete middle of a stack# without using additional data structure.  # Deletes middle of stack of size# n. Curr is current item numberclass Stack:    def __init__(self):        self.items = []          def isEmpty(self):        return self.items == []          def push(self, item):        self.items.append(item)          def pop(self):        return self.items.pop()          def peek(self):        return self.items[len(self.items)-1]          def size(self):        return len(self.items)          def deleteMid(st, n, curr) :     # If stack is empty or all items    # are traversed    if (st.isEmpty() or curr == n) :        return          # Remove current item    x = st.peek()    st.pop()          # Remove other items    deleteMid(st, n, curr+1)          # Put all items back except middle    if (curr != int(n/2)) :        st.push(x)  # Driver function to test above functionsst = Stack()  # push elements into the stackst.push('1')st.push('2')st.push('3')st.push('4')st.push('5')st.push('6')st.push('7')  deleteMid(st, st.size(), 0)  # Printing stack after deletion# of middle.while (st.isEmpty() == False) :    p = st.peek()    st.pop()    print (str(p) + " ", end="") # This code is contributed by# Manish Shaw (manishshaw1)
// C# code to delete middle of a stack// without using additional data structure.using System;using System.Collections.Generic; class GFG {         // Deletes middle of stack of size    // n. Curr is current item number    static void deleteMid(Stack<char> st,                          int n,                          int curr = 0)    {                 // If stack is empty or all        // items are traversed        if (st.Count == 0 || curr == n)            return;                 // Remove current item        char x = st.Peek();        st.Pop();                 // Remove other items        deleteMid(st, n, curr+1);                 // Put all items        // back except middle        if (curr != n / 2)            st.Push(x);    }         // Driver Code    public static void Main()    {        Stack<char> st = new Stack<char>();         // push elements into the stack        st.Push('1');        st.Push('2');        st.Push('3');        st.Push('4');        st.Push('5');        st.Push('6');        st.Push('7');             deleteMid(st, st.Count);             // Printing stack after        // deletion of middle.        while (st.Count != 0)        {            char p=st.Peek();            st.Pop();            Console.Write(p + " ");        }    }} // This code is contributed by// Manish Shaw (manishshaw1)
<script>    // Javascript code to delete middle of a stack    // without using additional data structure.         // Deletes middle of stack of size    // n. Curr is current item number    function deleteMid(st, n, curr)    {                  // If stack is empty or all items        // are traversed        if (st.length == 0 || curr == n)            return;                  // Remove current item        let x = st[st.length - 1];        st.pop();                  // Remove other items        deleteMid(st, n, curr+1);                  // Put all items back except middle        if (curr != parseInt(n/2, 10))            st.push(x);    }         let st = [];          // push elements into the stack    st.push('1');    st.push('2');    st.push('3');    st.push('4');    st.push('5');    st.push('6');    st.push('7');     deleteMid(st, st.length, 0);     // Printing stack after deletion    // of middle.    while (st.length > 0)    {      let p = st[st.length - 1];      st.pop();      document.write(p + " ");    }         // This code is contributed by suresh07.</script>
7 6 5 3 2 1 
Method – 2 (Iterative Solution)
In the above solution, we had used the recursion method but we can also do it by iterative method also.
C++
Java
// C++ code to delete middle of a stack with iterative method#include <bits/stdc++.h>using namespace std; // Deletes middle of stack of size n. Curr is current item numbervoid deleteMid(stack<char>& st){    int n = st.size();    stack<char> tempSt;    int count = 0;      // put first n/2 element of st in tempSt    while (count < n / 2) {        char c = st.top();        st.pop();        tempSt.push(c);        count++;    }      // delete middle element    st.pop();      // put all (n/2) element of tempSt in st    while (!tempSt.empty()) {        st.push(tempSt.top());        tempSt.pop();    }} // Driver function to test above functionsint main(){    stack<char> st;     // push elements into the stack    st.push('1');    st.push('2');    st.push('3');    st.push('4');    st.push('5');    st.push('6');    st.push('7');     deleteMid(st);     // Printing stack after deletion of middle.    while (!st.empty()) {        char p = st.top();        st.pop();        cout << p << " ";    }    return 0;}
// Java code to delete middle of a stack with iterative// methodimport java.util.Stack; @SuppressWarnings("unchecked")class Rextester{       // Deletes middle of stack of size n. Curr is current    // item number    static void deleteMid(Stack<Character> st)    {        int n = st.size();        Stack<Character> tempSt = new Stack();        int count = 0;        // put first n/2 element of st in tempSt        while (count < n / 2) {            char c = st.peek();            st.pop();            tempSt.push(c);            count++;        }        // delete middle element        st.pop();        // put all (n/2) element of tempSt in st        while (!tempSt.empty()) {            st.push(tempSt.peek());            tempSt.pop();        }    }     // Driver function to test above functions    public static void main(String args[])    {        Stack<Character> st = new Stack();         // push elements into the stack        st.push('1');        st.push('2');        st.push('3');        st.push('4');        st.push('5');        st.push('6');        st.push('7');         deleteMid(st);         // Printing stack after deletion of middle.        while (!st.empty()) {            char p = st.peek();            st.pop();            System.out.print(p + " ");        }    }} // This code is contributed by Lovely Jain
7 6 5 3 2 1 
Delete middle element of the stack | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersDelete middle element of the stack | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mxrBibfna7A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
manishshaw1
srivastavaharshit848
suresh07
rkumarjnvr
ajaymakvana
jainlovely450
STL
Recursion
Stack
Recursion
Stack
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.