Delete middle element of a stack
Last Updated :
10 Feb, 2023
Given a stack with push(), pop(), and empty() operations, The task is to delete the middle element 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 Easy And Brute Force Way To do it:
The Approach:
we have the stack we just put all the element of stack into a vector then traverse over the vector and put the print the element/push into stack ignoring the mid element for even (n/2) and for odd (ceil(n/2)).
C++
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
stack< char > st;
st.push( '1' );
st.push( '2' );
st.push( '3' );
st.push( '4' );
st.push( '5' );
st.push( '6' );
st.push( '7' );
vector< char >v;
while (!st.empty()){
v.push_back(st.top());
st.pop();
}
int n=v.size();
if (n%2==0){
int target=(n/2);
for ( int i=0;i<n;i++){
if (i==target) continue ;
st.push(v[i]);
}
} else {
int target= ceil (n/2);
for ( int i=0;i<n;i++){
if (i==target) continue ;
st.push(v[i]);
}
}
cout<< "Printing stack after deletion of middle: " ;
while (!st.empty()) {
char p = st.top();
st.pop();
cout << p << " " ;
}
return 0;
}
|
Java
import java.util.Stack;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Stack<Character> st = new Stack<Character>();
st.push( '1' );
st.push( '2' );
st.push( '3' );
st.push( '4' );
st.push( '5' );
st.push( '6' );
st.push( '7' );
Vector<Character> v = new Vector<Character>();
while (!st.empty()) {
v.add(st.pop());
}
int n = v.size();
if (n % 2 == 0 ) {
int target = (n / 2 );
for ( int i = 0 ; i < n; i++) {
if (i == target) continue ;
st.push(v.get(i));
}
} else {
int target = ( int ) Math.ceil(n / 2 );
for ( int i = 0 ; i < n; i++) {
if (i == target) continue ;
st.push(v.get(i));
}
}
System.out.print( "Printing stack after deletion of middle: " );
while (!st.empty()) {
char p = st.pop();
System.out.print(p + " " );
}
}
}
|
Python3
import math
st = []
st.append( '1' )
st.append( '2' )
st.append( '3' )
st.append( '4' )
st.append( '5' )
st.append( '6' )
st.append( '7' )
v = []
while ( len (st) > 0 ):
v.append(st[ 0 ])
del st[ 0 ]
n = len (v)
if n % 2 = = 0 :
target = math.floor(n / 2 )
for i in range ( 0 , n):
if i = = target:
continue
st.append(v[i])
else :
target = math.floor(n / 2 )
for i in range ( 0 , n):
if i = = target:
continue
st.append(v[i])
print ( "Printing stack after deletion of middle:" , end = " " )
while ( len (st) > 0 ):
p = st[ 0 ]
del st[ 0 ]
print (p, end = " " )
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static void Main(){
Stack< char > st = new Stack< char >();
st.Push( '1' );
st.Push( '2' );
st.Push( '3' );
st.Push( '4' );
st.Push( '5' );
st.Push( '6' );
st.Push( '7' );
List< char > v = new List< char >();
while (st.Count != 0){
v.Add(st.Peek());
st.Pop();
}
int n = v.Count;
int target = (n/2);
for ( int i = 0; i<n; i++){
if (i == target) continue ;
st.Push(v[i]);
}
Console.WriteLine( "Printing stack after deletion of middle : " );
while (st.Count != 0){
char p = st.Peek();
st.Pop();
Console.Write(p + " " );
}
}
}
|
Javascript
let st = [];
st.push( '1' );
st.push( '2' );
st.push( '3' );
st.push( '4' );
st.push( '5' );
st.push( '6' );
st.push( '7' );
let v = [];
while (st.length > 0){
v.push(st[0]);
st.shift();
}
let n = v.length;
if (n%2==0){
let target = Math.floor(n/2);
for (let i = 0; i < n; i++){
if (i==target){
continue ;
}
st.push(v[i]);
}
}
else {
let target = Math.floor(n/2);
for (let i = 0; i < n; i++){
if (i==target){
continue ;
}
st.push(v[i]);
}
}
console.log( "Printing stack after deletion of middle: " );
while (st.length > 0){
let p = st[0];
st.shift();
console.log(p + " " );
}
|
Output
Printing stack after deletion of middle: 1 2 3 5 6 7
Time Complexity: O(N), For the Traversing.
Auxiliary Space: O(N), For the Vector.
Delete the middle element of a stack using recursion:
Below is the idea to solve the problem
Remove elements of the stack recursively until the count of removed elements becomes half the initial size of the stack, now the top element is the middle element thus pop it and push the previously removed elements in the reverse order.
Follow the steps below to implement the idea:
- Store the stack size in a variable sizeofstack and a variable current to track the current size of stack.
- Recursively pop out the elements of the stack
- Pop the element from the stack and increment current by one then recur for the remaining stack.
- The base case would be when the current becomes equal to sizeofstack / 2 then pop the top element.
- Push the element that was popped before the recursive call.
Below is the Implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void deleteMid_util(stack< char >&s, int sizeOfStack, int current)
{
if (current==sizeOfStack/2)
{
s.pop();
return ;
}
int x = s.top();
s.pop();
current+=1;
deleteMid_util(s,sizeOfStack,current);
s.push(x);
}
void deleteMid(stack< char >&s, int sizeOfStack)
{
deleteMid_util(s,sizeOfStack,0);
}
int main()
{
stack< char > st;
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());
while (!st.empty())
{
char p=st.top();
st.pop();
cout << p << " " ;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static void deleteMid(Stack<Character> st,
int n, int curr)
{
if (st.empty() || curr == n)
return ;
char x = st.pop();
deleteMid(st, n, curr+ 1 );
if (curr != n/ 2 )
st.push(x);
}
public static void main(String args[])
{
Stack<Character> st =
new Stack<Character>();
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 );
while (!st.empty())
{
char p=st.pop();
System.out.print(p + " " );
}
}
}
|
Python3
class 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 (st.isEmpty() or curr = = n) :
return
x = st.peek()
st.pop()
deleteMid(st, n, curr + 1 )
if (curr ! = int (n / 2 )) :
st.push(x)
st = 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 )
while (st.isEmpty() = = False ) :
p = st.peek()
st.pop()
print ( str (p) + " " , end = "")
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void deleteMid(Stack< char > st,
int n,
int curr = 0)
{
if (st.Count == 0 || curr == n)
return ;
char x = st.Peek();
st.Pop();
deleteMid(st, n, curr+1);
if (curr != n / 2)
st.Push(x);
}
public static void Main()
{
Stack< char > st = new Stack< char >();
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);
while (st.Count != 0)
{
char p=st.Peek();
st.Pop();
Console.Write(p + " " );
}
}
}
|
Javascript
<script>
function deleteMid(st, n, curr)
{
if (st.length == 0 || curr == n)
return ;
let x = st[st.length - 1];
st.pop();
deleteMid(st, n, curr+1);
if (curr != parseInt(n/2, 10))
st.push(x);
}
let st = [];
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);
while (st.length > 0)
{
let p = st[st.length - 1];
st.pop();
document.write(p + " " );
}
</script>
|
Time Complexity: O(N), For the recursive calls
Auxiliary Space: O(N), For the Recursion call Stack
Delete middle element of a stack using another stack:
Pop the elements above the middle element of the given stack and use a temp stack to store these popped elements. Then pop the middle element and push the elements of the temp stack in the given stack.
Follow the below steps to implement the idea:
- Initialize an empty stack temp and a variable count with 0.
- Run a while loop till count becomes equal to half the initial size of the given stack
- Pop the element of the given stack and push them in temp.
- Pop the top element from the given stack.
- Run a while loop till temp becomes empty.
- Push the element of temp and push them in the given stack .
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void deleteMid(stack< char >& st)
{
int n = st.size();
stack< char > tempSt;
int count = 0;
while (count < n / 2) {
char c = st.top();
st.pop();
tempSt.push(c);
count++;
}
st.pop();
while (!tempSt.empty()) {
st.push(tempSt.top());
tempSt.pop();
}
}
int main()
{
stack< char > st;
st.push( '1' );
st.push( '2' );
st.push( '3' );
st.push( '4' );
st.push( '5' );
st.push( '6' );
st.push( '7' );
deleteMid(st);
while (!st.empty()) {
char p = st.top();
st.pop();
cout << p << " " ;
}
return 0;
}
|
Java
import java.util.Stack;
@SuppressWarnings ( "unchecked" )
class Rextester
{
static void deleteMid(Stack<Character> st)
{
int n = st.size();
Stack<Character> tempSt = new Stack();
int count = 0 ;
while (count < n / 2 ) {
char c = st.peek();
st.pop();
tempSt.push(c);
count++;
}
st.pop();
while (!tempSt.empty()) {
st.push(tempSt.peek());
tempSt.pop();
}
}
public static void main(String args[])
{
Stack<Character> st = new Stack();
st.push( '1' );
st.push( '2' );
st.push( '3' );
st.push( '4' );
st.push( '5' );
st.push( '6' );
st.push( '7' );
deleteMid(st);
while (!st.empty()) {
char p = st.peek();
st.pop();
System.out.print(p + " " );
}
}
}
|
Python3
def deleteMid(st):
n = len (st)
tempSt = []
count = 0
while (count < (n / 2 ) - 1 ):
c = st[ 0 ]
st.pop( 0 )
tempSt.insert( 0 , c)
count = count + 1
st.pop( 0 )
while ( len (tempSt) ! = 0 ):
st.insert( 0 , tempSt[ 0 ])
tempSt.pop( 0 )
st = []
st.insert( 0 , 1 )
st.insert( 0 , 2 )
st.insert( 0 , 3 )
st.insert( 0 , 4 )
st.insert( 0 , 5 )
st.insert( 0 , 6 )
st.insert( 0 , 7 )
deleteMid(st)
while ( len (st) ! = 0 ):
p = st[ 0 ]
st.pop( 0 )
print (p, " " )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void deleteMid(Stack< char > st, int n)
{
Stack< char > tempSt = new Stack< char >();
int count = 0;
while (count < n / 2) {
char c = st.Peek();
st.Pop();
tempSt.Push(c);
count++;
}
st.Pop();
while (tempSt.Count != 0) {
st.Push(tempSt.Peek());
tempSt.Pop();
}
}
public static void Main()
{
Stack< char > st = new Stack< char >();
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);
while (st.Count != 0)
{
char p=st.Peek();
st.Pop();
Console.Write(p + " " );
}
}
}
|
Javascript
function deleteMid(st)
{
let n = st.length;
let tempSt=[];
let count = 0;
while (count < (n / 2)-1) {
let c = st[0];
st.shift();
tempSt.unshift(c);
count++;
}
st.shift();
while (tempSt.length!=0) {
st.unshift(tempSt[0]);
tempSt.shift();
}
}
let st=[];
st.unshift( '1' );
st.unshift( '2' );
st.unshift( '3' );
st.unshift( '4' );
st.unshift( '5' );
st.unshift( '6' );
st.unshift( '7' );
deleteMid(st);
while (st.length!=0) {
let p = st[0];
st.shift();
console.log(p , " " );
}
|
Time Complexity: O(N), For the while loop
Auxiliary Space: O(N), for temp stack space.
Please Login to comment...