In this problem, you need to simulate stack operations.
Example
Consider the stack operations in the first example:
Algorithm implementation
Declare the stack.
stack<int> s;Read the number of operations .
scanf("%d", &n);Sequentially process operations.
for (int i = 0; i < n; i++)
{
scanf("%d", &op);Insert the element, push operation.
if (op == 1)
{
scanf("%d", &x);
s.push(x);
}Remove the element, pop operation.
else
{
printf("%d\n", s.top());
s.pop();
}
}Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
Stack<Integer> s = new Stack<Integer>();
int n = con.nextInt();
for (int i = 0; i < n; i++)
{
int op = con.nextInt();
if (op == 1)
{
int x = con.nextInt();
s.push(x);
}
else
System.out.println(s.pop());
}
con.close();
}
} Java implementation — class MyStack
import java.util.*;
class MyStack
{
private Vector<Integer> v;
MyStack()
{
v = new Vector<Integer>();
}
public void push(int x)
{
v.add(x);
}
public int pop()
{
int last = v.lastElement();
v.remove(v.size() - 1);
return last;
}
}
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
MyStack s = new MyStack();
int n = con.nextInt();
for (int i = 0; i < n; i++)
{
int op = con.nextInt();
if (op == 1)
{
int x = con.nextInt();
s.push(x);
}
else
System.out.println(s.pop());
}
con.close();
}
} Python implementation
Read the number of operations .
n = int(input())Use the list to simulate the stack.
stack = []Sequentially process operations.
for i in range(n):
lst = list(map(int,input().split()))Insert the element, push operation.
if (lst[0] == 1):
stack.append(lst[1])Remove the element, pop operation.
else:
print(stack.pop())