CS/알고리즘_문제풀이(파이썬)

큐 구현하기

Jedy_Kim 2021. 7. 6. 14:50
728x90

문제

이 문제에서는 큐를 구현한다. 큐는 다음 세 개의 연산을 지원한다.

  • Push X : 큐에 정수 X를 push한다. 만약 rear 포인터가 더 이상 뒤로 갈 수 없다면, “Overflow”를 출력한다.
  • Pop : 큐에서 정수 하나를 pop한다. 만약 front 포인터가 더 이상 뒤로 갈 수 없다면, “Underflow”를 출력한다.
  • Front : 큐의 front에 있는 정수를 출력한다. 만약 큐가 비어있다면 “NULL”을 출력한다.

크기가 n인 배열로 만든 큐에 m개의 연산을 하는 프로그램을 작성하시오. 입력의 편의를 위해서 Push는 “1”, Pop은 “2”, Front는 “3”으로 표현한다.

 

입력

첫째 줄에 큐를 만들 수 있는 배열의 크기 n, 연산의 개수 m이 주어진다. ( 1 ≤ n ≤ 100, 1 ≤ m ≤ 1,000 ) 두 번째 줄부터 연산이 주어진다. 1은 Push, 2는 Pop, 3은 Front 연산을 의미한다.  

출력

연산의 결과를 출력한다.

 

예제 입력

4 15

1 1

1 2

1 3

3

2

2

3

1 4

1 5

3

2

2

1 6

2

3

예제 출력

1

3

Overflow

3

Overflow

Underflow

 

#코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import sys
 
def push(value):
  global front_cursor, rear_cursor, n, data
  if rear_cursor >= n:
    print('Overflow')
  else:
    data[rear_cursor] = value
    rear_cursor      += 1
 
def pop():
  global front_cursor, rear_cursor, n, data
  if front_cursor >= rear_cursor:
    print('Underflow')
  else:
    data[front_cursor] = 0
    front_cursor += 1
 
def front(): 
  if data[front_cursor] == 0:
    print('NULL')
  else:
    print(data[front_cursor])
 
if __name__ == "__main__":
  input = sys.stdin.readline
  
  n, m   = map(int, input().split()) 
  arr    = [list(map(int, input().split())) for _ in range(m)]
  
  data   = [0]*110
  front_cursor  = 0
  rear_cursor   = 0
  
  for item in arr: 
    if item[0== 1:
      push(item[1])
    elif item[0== 2:
      pop()
    elif item[0== 3:
      front()
cs

 

반응형

'CS > 알고리즘_문제풀이(파이썬)' 카테고리의 다른 글

트리에서의 거리  (0) 2021.07.07
트리의 높이  (0) 2021.07.07
  (0) 2021.07.05
구간의 합집합  (0) 2021.07.05
중복 없는 구간  (0) 2021.07.02