Stack Operations
Python
Easy
3 views
Problem Description
Read q commands: PUSH x or POP. Start empty list. POP on empty does nothing. At end output size and last element (or EMPTY).
Input Format
First line q. Next q lines commands.
Output Format
One line result.
Sample Test Case
Input:
6
PUSH 5
PUSH 2
POP
POP
POP
PUSH 9
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
st=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if not parts: continue
if parts[0]=='PUSH':
st.append(int(parts[1]))
else:
if st:
st.pop()
if not st:
sys.stdout.write('0 EMPTY')
else:
sys.stdout.write(f'{len(st)} {st[-1]}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!