Stack Designer
Problem Description​
You are given an array arr of size N. You need to push the elements of the array into a stack and then print them while popping.
Examples​
Example 1:
Input:
n = 5
arr = {1 2 3 4 5}
Output:
5 4 3 2 1
Example 2:
Input:
n = 7
arr = {1 6 43 1 2 0 5}
Output:
5 0 2 1 43 6 1
Constraints​
1 ≤ Ai ≤ 10^7
Solution for Stack Designer​
Code in Different Languages​
- Python
- Java
- C++
class Stack:
def __init__(self):
self.stack = []
def push(self, arr):
for item in arr:
self.stack.append(item)
return self.stack
def pop_all(self):
while self.stack:
print(self.stack.pop(), end=" ")
# Example usage
arr = [1, 2, 3, 4, 5]
n = len(arr)
s = Stack()
s.push(arr)
s.pop_all()
# Output: 5 4 3 2 1
import java.util.Stack;
public class Main {
public static Stack<Integer> _push(int arr[], int n) {
Stack<Integer> s = new Stack<>();
for (int i = 0; i < n; ++i) {
s.push(arr[i]);
}
return s;
}
public static void _pop(Stack<Integer> s) {
while (!s.empty()) {
System.out.print(s.pop() + " ");
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
Stack<Integer> s = _push(arr, n);
_pop(s);
// Output: 5 4 3 2 1
}
}
stack<int>_push(int arr[],int n)
{
//return a stack with all elements of arr inserted in it
stack<int> s;
for (int i = 0; i < n; ++i) {
s.push(arr[i]);
}
return s;
}
/* _pop function to print elements of the stack
remove as well
*/
void _pop(stack<int> s)
{
//print top and pop for each element until it becomes empty
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
References​
- GeekForGeeks Problem: Stack Designer