Pages

Friday, September 19, 2025

Push element at the bottom of the Stack

 import java.util.*;


// Push element at the bottom of stack

class StackB {

    

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

        if (s.isEmpty()) {  // ✅ base case

            s.push(data);

            return;

        }

        

        int top = s.pop();              // store top

        pushAtBottom(s, data);          // recurse until empty

        s.push(top);                    // push top back

    }

    

    public static void main(String[] args) {

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

        s.push(1);

        s.push(2);

        s.push(3);

        

        pushAtBottom(s, 4);  // insert at bottom

        

        while(!s.isEmpty()) {

            System.out.println(s.pop()); // we do popping To demonstrate the result of inserting at the bottom.

        }

    }

}


No comments:

Post a Comment

how to become red on codeforces by Errichto Algorithms | explained simply in a blog

 Yes. I found an available transcript of the video and summarized it simply. The video is “How To Become Red Coder? (codeforces.com)” by Err...