BM Balmiki Mandal 06 May 2023 4 views 0 comments Core Java

How to Reverse a Stack in Java

How to Reverse a Stack in Java

Reversing a stack in Java means reversing the order of elements in a stack. A stack is a data structure that follows the Last-In-First-Out (LIFO) principle, which means that the last element added to the stack is the first one to be removed. To reverse a stack, you need to reverse the order of the elements so that the first element becomes the last one, the second element becomes the second-to-last one, and so on.

To reverse a stack in Java, you can use a temporary stack to hold the reversed elements. Here's an example implementation:

import java.util.*;

public class ReverseStack {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);

        System.out.println("Original stack: " + stack);

        Stack<Integer> reversedStack = reverseStack(stack);

        System.out.println("Reversed stack: " + reversedStack);
    }

    public static Stack<Integer> reverseStack(Stack<Integer> stack) {
        Stack<Integer> tempStack = new Stack<>();

        while (!stack.isEmpty()) {
            int element = stack.pop();
            tempStack.push(element);
        }

        return tempStack;
    }
}

In this example, we create a stack with the values 1 to 5 and print the original stack. We then call the reverseStack() method to reverse the stack and print the reversed stack.

The reverseStack() method takes the original stack as an argument and creates a new temporary stack. It then pops elements from the original stack and pushes them onto the temporary stack, effectively reversing the order of the elements. Finally, it returns the reversed stack.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023