Stack Class
Programming Interview
Easy
8 views
Problem Description
You will receive q commands: PUSH x, POP, TOP. Create Stack class and for TOP output value or EMPTY.
Input Format
First line q. Next q lines commands.
Output Format
Outputs for TOP.
Sample Test Case
Input:
7
PUSH 5
TOP
PUSH 3
TOP
POP
TOP
POP
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
class Stack:
def __init__(self):
self.a=[]
def push(self,x):
self.a.append(x)
def pop(self):
if self.a:
self.a.pop()
def top(self):
return self.a[-1] if self.a else None
st=Stack()
out=[]
for i in range(q):
parts=(lines[1+i] if 1+i<len(lines) else '').split()
if not parts: continue
if parts[0]=='PUSH':
st.push(int(parts[1]))
elif parts[0]=='POP':
st.pop()
else:
v=st.top()
out.append(str(v) if v is not None else 'EMPTY')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!