정리
백준 10845번: 큐 본문
백준 10845번: 큐

- 자료구조 중 큐(queue)를 사용해서 푸는 문제입니다.
- Java에서는 java.util.LinkedList 와 java.util.Queue 를 import 하면 라이브러리를 이용해서 쉽게 풀 수 있습니다.
- 아래 코드에서 사용한 기능은 다음과 같습니다.
- add() : 큐에 데이터를 추가
- isEmpty() : 큐가 비었는지 찼는지 확인
- poll() : 큐에 가장 먼저 추가 된 데이터 출력 이후 큐에서 삭제
- size() : 큐에 저장 된 데이터 수 출력
- peek() : 큐에 가장 먼저 추가 된 데이터 출력
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.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
public class Main{ | |
public static void main(String[] args) { | |
Queue<Integer> queue = new LinkedList<>(); | |
Scanner sc = new Scanner(System.in); | |
int n = sc.nextInt(); | |
int a = 0; | |
for(int i = 0; i < n; i++){ | |
String input = sc.next(); | |
if(input.contains("push")){ | |
a = sc.nextInt(); | |
queue.add(a); | |
} | |
else if(input.contains("pop")){ | |
System.out.println(queue.isEmpty() ? -1 : queue.poll()); | |
} | |
else if(input.contains("size")){ | |
System.out.println(queue.size()); | |
} | |
else if(input.contains("empty")){ | |
System.out.println(queue.isEmpty() ? 1 : 0); | |
} | |
else if(input.contains("front")){ | |
System.out.println(queue.isEmpty() ? -1 : queue.peek()); | |
} | |
else if(input.contains("back")){ | |
System.out.println(queue.isEmpty() ? -1 : a); | |
} | |
} | |
sc.close(); | |
} | |
} |
'Programming > 백준 BOJ' 카테고리의 다른 글
백준 1092번: 배 (0) | 2020.07.27 |
---|---|
백준 2512번: 예산 (0) | 2020.07.23 |
백준 10828번: 스택 (0) | 2020.07.11 |
백준 1024번: 수열의 합 (0) | 2020.07.10 |
백준 1010번: 다리 놓기 (0) | 2020.07.08 |
Comments