Delete All Even Elements from a Stack in Java



In this tutorial, we will learn to remove all even numbers from the given stack containing integer values. In Java, the stack is a data structure that works based on the Last-In-First-Out (LIFO) principle. It means, whatever elements you have added in the last, you can get it first.

Removing even elements from the stack is useful in many real-world scenarios. For example, you can use this technique to filter the data from the stack. However, filtering logic can differ according to the scenario. In our case, we will remove even numbers and filter odd numbers. In other cases, you might need to filter string characters according to the specific conditions, but the approaches explained in this tutorial will work in all scenarios.

Problem Statement

Given a stack write a program in Java to delete all even elements from it.

Input 1

stack = [1, 2, 3, 4, 5]

Output 1

[1, 3, 5]

Explanation: We have removed 2 and 4 from the stack as they are even numbers.

Input 2

stack = [1, 7, 3, 11, 9]
Output 2
[1, 7, 3, 11, 9]

Explanation: The stack doesn't have even numbers. So, we don't need to remove any elements.

Different Approaches

Here, we will learn 2 different approaches to removing even elements from the stack

Using an Auxiliary Stack

The first approach uses the auxiliary stack, which means a temporary stack to remove all even numbers from the given stack. In this approach, we will create a temporary stack. After that, we will traverse through each element of the stack and pop element from the stack. If the popped element is even, we push it to the temporary stack.

In the second pass, we will pop the element from the temporary stack until it becomes empty, and push it to the original stack again. Now, the original stack contains only odd numbers.

Below are the steps to delete all even elements from a stack using Auxiliary Stack ?

  • Import the Stack class from java.util package.
  • Initialize a temporary stack tempStack to hold odd elements.
  • Start a loop to traverse the original stack until it's empty.
  • Pop the top element from the original stack.
  • Check if the element is odd (i.e., element % 2 is not equal to 0).
  • If the element is odd, push it onto the tempStack.
  • Start a loop to transfer elements back from tempStack to the original stack.
  • Pop the top element from tempStackand push it back onto the original stack.

Example

Here is the code for the above auxiliary stack approach ?

import java.util.Stack;
public class RemoveEvenElements {
    public static void removeEven(Stack stack) {
        Stack tempStack = new Stack<>(); // Create a temporary stack
        // Transfer elements from the original stack to the temporary stack
        while (!stack.isEmpty()) {
            int element = stack.pop();
            if (element % 2 != 0) { // Check if the element is odd
                tempStack.push(element); // Push odd elements to the temporary stack
            }
        }
        // Transfer elements back to the original stack
        while (!tempStack.isEmpty()) {
            stack.push(tempStack.pop());
        }
    }
    public static void main(String[] args) {
        Stack stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        removeEven(stack);
        System.out.println(stack); // Output will be [1, 3, 5]
    }
}

Output

[1, 3, 5]

Time Complexity: O(n) as we traverse through the original stack. Here, `n` is the size of the stack. In the second pass, we traverse the temporary stack, which will have less or equal number of elements to the original stack.

Space Complexity: O(n), as we use the temporary stack.

Using Recursion

The second approach traverses the stack recursively and removes the even elements. Let's understand the step-by-step algorithm to learn how this approach works.

Algorithm

  • First, we will import the Stack class from java.util package.
  • Check if the stack is empty. If the stack is empty, return from the function (base case).
  • Pop the top element from the stack and store it in a variable element.
  • Recursively call to remove the even function to process the rest of the stack.
  • After the recursive call, check if the element is odd (i.e., element % 2 != 0). If the element is odd, push it back onto the stack.
  • The recursion will continue until all elements are processed, removing even numbers and retaining odd numbers in the stack.
  • Once the recursion is complete, the stack will only contain odd elements in the same order as they were originally placed.

Example

Below is the code for the above approach ?

import java.util.Stack;
public class RemoveEvenElements {
    public static void removeEven(Stack stack) {
        if (stack.isEmpty()) {
            return; // Base case: stack is empty
        }
        int element = stack.pop(); // Pop the top element
        removeEven(stack); // Recursive call to process the rest of the stack
        if (element % 2 != 0) { // Check if the element is odd
            stack.push(element); // Push odd elements back into the stack
        }
    }
    public static void main(String[] args) {
        Stack stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        removeEven(stack);
        System.out.println(stack); // Output will be [1, 3, 5]
    }
}

Output

[1, 3, 5]

Time Complexity: O(n) as we recursively traverse through the original stack. Here, `n` is the size of the stack. 
Space Complexity: O(n). It is used for the for the recursive stack.

Conclusion

We have learned 2 different approaches to remove even numbers from the stack in this tutorial. The first approach is easy to understand for beginners. Using this similar code, you can perform different kinds of filtering operations on the stack. For example, to remove odd numbers from the stack, you just need to change the 'if (element % 2 != 0)' condition to 'if (element % 2 = 0)'. In some cases, you might need to write multiple conditions to filter elements from the stack.

Shubham B Vora
Shubham B Vora

Expert Technical Content Writer | Specializing in Technology, AI, and Programming | Helping Brands Communicate Effectively

Updated on: 2024-09-23T19:09:09+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements