본문 바로가기
Baekjoon/큐, 덱

[백준] 18258번, 큐 2 | (python, 파이썬)

by 성재심 2021. 7. 20.

큐 개념정리

 

 

[개념정리] 큐(Queue)| (python, 파이썬)

큐(Queue)란? ○큐(Queue)  ▷ Queue은 가장 최근에 저장된 값 다음에 저장되며, 가장 처음에 저장된 값이 먼저 나가는 자료구조이다.  ▷ 큐는 enqueue 연산으로 값을 차례대로 삽입하고, dequeue 연산으

corin-jaesung.tistory.com


문제 링크

 

 

18258번: 큐 2

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net


문제


정답코드

import sys
class Queue :
    def __init__(self):
        self.items = []
        self.front_index = 0

    def push(self,x) :
        self.items.append(x)

    def pop(self) :
        if len(self.items) == 0 or len(self.items) == self.front_index :
            return -1
        else :
            k = self.items[self.front_index]
            self.front_index += 1
            return k

    def size(self) :
        return len(self.items) - self.front_index

    def empty(self) :
        if len(self.items) == 0 or len(self.items) == self.front_index: 
            return 1
        else : return 0
    def front(self) :
        if len(self.items) == 0 or len(self.items) == self.front_index: 
            return -1
        else : 
            return self.items[self.front_index]
    def back(self) :
        if len(self.items) == 0 or len(self.items) == self.front_index:
            return -1
        else : return self.items[-1]
Q = Queue()
n = int(input())

for i in range(n) :
    cmd = sys.stdin.readline().split()
    if cmd[0] == 'push' :
        Q.push(int(cmd[1]))
    elif cmd[0] == 'pop' :
        print(Q.pop())
    elif cmd[0] == 'size' :
        print(Q.size())
    elif cmd[0] == 'empty' :
        print(Q.empty())
    elif cmd[0] == 'front' :
        print(Q.front())
    elif cmd[0] == 'back' :
        print(Q.back())
    else :
        print("input error")

▶개념정리에서 설명한 클래스에서 문제에서 제시한 함수이름으로만 바꿨을뿐, 기존 개념을 유지한다.

▶빠른 입력을 위해서 sys.stdin.readline() 사용 필수 !

'Baekjoon > 큐, 덱' 카테고리의 다른 글

[백준] 2164번, 카드 2 | (python, 파이썬)  (0) 2021.07.20