반응형
문제
이 문제에서는 큐를 구현한다. 큐는 다음 세 개의 연산을 지원한다.
- Push X : 큐에 정수 X를 push한다. 만약 rear 포인터가 더 이상 뒤로 갈 수 없다면, “Overflow”를 출력한다.
- Pop : 큐에서 정수 하나를 pop한다. 만약 front 포인터가 더 이상 뒤로 갈 수 없다면, “Underflow”를 출력한다.
- Front : 큐의 front에 있는 정수를 출력한다. 만약 큐가 비어있다면 “NULL”을 출력한다.
크기가 n인 큐에 m개의 연산을 하는 프로그램을 작성하시오. 입력의 편의를 위해서 Push는 “1”, Pop은 “2”, Top은 “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
NULL
Underflow, Overflow 범위에 주의하자.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Queue { | |
static int [] queue; | |
static int n, f, r; | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
n = sc.nextInt(); | |
int m = sc.nextInt(); | |
queue = new int[n+1]; | |
for(int i=0; i<m; i++) { | |
int x = sc.nextInt(); | |
if(x==1) { | |
int y = sc.nextInt(); | |
push(y); | |
} else if(x==2) { | |
pop(); | |
} else { | |
// x==3 | |
front(); | |
} | |
} | |
} | |
public static void push(int x) { | |
if(r-f >= n || r >= n) { | |
System.out.println("Overflow"); | |
} else { | |
queue[r++] = x; | |
} | |
} | |
public static void pop() { | |
if(r-f <= 0) { | |
System.out.println("Underflow"); | |
} else { | |
f++; | |
} | |
} | |
public static void front() { | |
if(f==r) { | |
System.out.println("NULL"); | |
} else { | |
System.out.println(queue[f]); | |
} | |
} | |
} |
반응형
'자료구조' 카테고리의 다른 글
트리 (Tree) (0) | 2019.02.23 |
---|---|
원형 큐 구현하기 (0) | 2019.02.20 |
원형 큐 (Circular Queue) (0) | 2019.02.20 |
큐 ( Queue ) (0) | 2019.02.19 |
스택 (Stack) (0) | 2019.02.10 |