/** * @author lautturi.com * Java example: how to remove minimum element from stack */ import java.util.*; public class Lautturi { // delete remove minimum element from stack public static void removeMin(Stack<Integer> stack) { Integer min = stack.peek(); Integer e; Stack<Integer> newStack = new Stack<Integer>(); // find out the min value in stack while (!stack.isEmpty()) { e = stack.pop(); newStack.push(e); if (e < min) { min = e; } } stack.clear(); while (!newStack.isEmpty()) { e = newStack.pop(); if (e != min) { stack.push(e); } } } public static void main(String[] args) { Stack<Integer> stack= new Stack<Integer>(); stack.push(3); stack.push(7); stack.push(15); stack.push(12); stack.push(7); stack.push(1); stack.push(15); stack.push(8); System.out.println("Stack: " + stack); removeMin(stack); System.out.println("Stack: " + stack); } }
output:
Stack: [3, 7, 15, 12, 7, 1, 15, 8] Stack: [3, 7, 15, 12, 7, 15, 8]