java
정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
Scanner와 System.out.println은 시간 초과가 뜨기 때문에 BufferedReader와 BufferedWrite를 사용해 문제를 풀었다.
큐를 활용한 기본적인 문제이다. 큐와 관련된 명령어들을 잘 숙지해야겠다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
Queue<Integer> queue = new LinkedList<>();
int lastValue = 0;
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
String command = br.readLine();
if (command.startsWith("push")) {
int value = Integer.parseInt(command.substring(5));
queue.add(value);
lastValue = value;
} else if (command.equals("pop")) {
if (queue.isEmpty()) {
bw.write("-1\n");
} else {
bw.write(queue.poll() + "\n");
}
} else if (command.equals("size")) {
bw.write(queue.size() + "\n");
} else if (command.equals("empty")) {
bw.write((queue.isEmpty() ? 1 : 0) + "\n");
} else if (command.equals("front")) {
if (queue.isEmpty()) {
bw.write("-1\n");
} else {
bw.write(queue.peek() + "\n");
}
} else if (command.equals("back")) {
if (queue.isEmpty()) {
bw.write("-1\n");
} else {
bw.write(lastValue + "\n");
}
}
}
br.close();
bw.flush();
bw.close();
}
}
Java들어가며 소프트웨어가 처리해야 하는 데이터 양이 늘어날수록, 단순히 기능 구현만으로는 성능과 효율을 보장하기 어렵습니다. 특히…
들어가며 소프트웨어를 구현할 때 성능 최적화나 안정성을 높이려면, 단순히 고수준 코드만 신경 쓰는 것을 넘어…
들어가며 소프트웨어가 복잡해질수록, 단순히 알고리즘의 시간복잡도만으로는 모든 문제를 해결할 수 없습니다. 특히 운영체제 수준에서는 다중…
들어가며 복잡한 소프트웨어가 원활히 동작하려면 단순히 코드만 잘 짜는 것으로는 부족합니다. 트랜잭션 처리나 대규모 데이터…
들어가며 소프트웨어를 개발할 때 메모리 관리 방식은 프로그램의 안정성과 성능을 좌우하는 핵심 요소입니다. 특히 자바스크립트,…
들어가며 소프트웨어 개발자는 코드가 어떻게 실행되는지 정확히 이해해야 할 필요가 있습니다. 우리가 작성한 프로그램은 결국…