Pages

Tuesday, September 23, 2025

Reverse a Stack (Revision)

 import java.util.Stack;


class StackB {

    

    

    static public void pushAtBottom(Stack<Integer> s, int data) {

        if(s.isEmpty()) {

            s.push(data);

            return;

        }

        

        int top = s.pop();

        pushAtBottom(s, data);

        s.push(top);

    }

    

    public static void reverseStack(Stack<Integer> s) {

        if(s.isEmpty()) {

            return;

        }

        

        int top = s.pop(); // remove each element from top

        reverseStack(s);

        pushAtBottom(s, top);

    }

    

    

    

    public static void main(String[] args) {

    Stack<Integer> s = new Stack<>();

    

    s.push(1);

    s.push(2);

    s.push(3);

    

    System.out.println(s);

    

    reverseStack(s);

    

    System.out.println(s);

    }

}

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...