내가 시도한 방법
사실 stack을 구현하기만 하면 되는 문제라 크게 어려움은 없었지만,
두 가지 버전으로 stack
을 구현하는 것을 연습했다.
1. .append()
와 .pop()
을 사용한 버전
2. top
을 이용하여 구현한 버전 쓰지 않은 버전
그리고 top
을 이용한 방법이 항상 빠른 것은 아니다는 것을 기록하려고 코드를 올려본다.
추가로 이 문제에서 잠깐 고민한 곳이 데이터 입력인데('push'
일때만 stack
에 추가할 값이 들어오는데) 이 부분을 패킹(*X
) 연산자를 통해 해결했다.
push
가 나오면, .append()
를 이용해서 추가pop
이 나오면, 빈 배열이 아닐 때에만 .pop()
을 이용해서 제거from sys import stdin
N = int(input())
lst = []
for _ in range(N):
command, *X = stdin.readline().rstrip().split()
if command == 'push':
lst.append(int(*X))
elif command == 'pop':
if not lst:
print(-1)
else:
print(lst.pop())
elif command == 'size':
print(len(lst))
elif command == 'empty':
if not lst:
print(1)
else:
print(0)
else:
if not lst:
print(-1)
else:
print(lst[-1])
top
)를 활용한 코드top
을 이용해서 stack
에 값이 추가될 때 +1stack
이 비었는지(top
이 음수), size
가 몇인지(top
+1) 등 추가 연산하면 됨top
으로 stack
을 구현하려면, 처음에 stack
길이 설정을 N으로 해야해서....쓸 데 없는 빈 공간이 많이 만들어져서 그런지...그렇게 빠르지 않았다. 심지어 위의 코드보다 더 느렸다.from sys import stdin
N = int(input())
lst = [0] * N
top = -1
for _ in range(N):
command, *X = stdin.readline().rstrip().split()
if command == 'push':
top += 1
lst[top] = int(*X)
elif command == 'pop':
if top < 0:
print(-1)
else:
print(lst[top])
top -= 1
elif command == 'size':
print(top+1)
elif command == 'empty':
if top < 0:
print(1)
else:
print(0)
else:
if top < 0:
print(-1)
else:
print(lst[top])