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