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

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...