[백준] 10845번(큐)

·2023년 5월 1일

백준 문제풀이

목록 보기
58/159

백준 10845번


최종 제출 코드

import sys

input = sys.stdin.readline
n = int(input().rstrip())
stack = []
size = 0
front = 0
back = 0

for i in range(n):
  command = input().rstrip()

  if command[0:4] == 'push':
    stack.append(int(command[5:]))
    back += 1
    size += 1
  elif command == 'pop':
    if front == back:
      print(-1)
    else:
      print(stack[front])
      front += 1
      size -= 1
  elif command == 'size' :
    print(size)
  elif command == 'empty':
    if size ==0:
      print(1)
    else:
      print(0)
  elif command == 'front':
    if size == 0:
      print(-1)
    else:
      print(stack[front])
  else:
    if size == 0:
      print(-1)
    else:
      print(stack[back-1])

size, front, back 변수를 선언하여 활용

◼ 그러나 생각해보니...

  • 굳이 위와 같은 변수를 사용하지 않아도 리스트의 기본 연산만으로 구현 가능
  • 그리고 위와 같은 방식은 실제로 필요없는 원소들을 삭제하지 않기 때문에 메모리 낭비
    pop 연산에서 실제로 원소를 삭제하는 방식으로 코드 수정

수정한 코드

import sys

input = sys.stdin.readline
n = int(input().rstrip())
stack = []

for i in range(n):
  command = input().rstrip()

  if command[0:4] == 'push':
    stack.append(int(command[5:]))

  elif command == 'pop':
    if len(stack)==0:
      print(-1)
    else:
      print(stack[0])
      del stack[0]
  elif command == 'size' :
    print(len(stack))
  elif command == 'empty':
    if len(stack)==0:
      print(1)
    else:
      print(0)
  elif command == 'front':
    if len(stack)==0:
      print(-1)
    else:
      print(stack[0])
  else:
    if len(stack) == 0:
      print(-1)
    else:
      print(stack[-1])

실행 결과

◼ 막상 실행해보니 코드 길이를 제외한 메모리, 실행시간 모두 동일...

profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글