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

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

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