Notice
Recent Posts
Recent Comments
Link
«   2026/01   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Development Log

[Baekjoon] 10845번: 큐 본문

Coding Test/Baekjoon

[Baekjoon] 10845번: 큐

gu-su 2022. 2. 14. 05:02

소스코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

class Queue{
	
	private int[] queueArr;
	private int frontIndex = -1;
	private int backIndex = -1;
	
	Queue(int totalCmdNum){
		queueArr = new int[totalCmdNum];
	}
	
	void push(int value) {
		
		queueArr[++backIndex] = value;
		
		if(frontIndex == -1) {
			++frontIndex;
		}
	}
	
	int pop() {
		
		if(frontIndex < 0) {
			return -1;
		}
		
		int value = queueArr[frontIndex];
		queueArr[frontIndex++] = 0;
		
		if(frontIndex > backIndex) {
			frontIndex = -1;
			backIndex = -1;
		}
		
		return value;
		
	}
	
	int size() {
		
		if(empty() == 1) {
			return 0;
		}
		
		return backIndex - frontIndex + 1;
	}
	
	int empty() {
		if(frontIndex < 0) {
			return 1;
		}
		
		return 0;
	}
	
	int front() {
		
		if(frontIndex < 0) {
			return -1;
		}
		
		return queueArr[frontIndex];
	}
	
	int back() {
		if(frontIndex < 0) {
			return -1;
		}
		
		return queueArr[backIndex]; 
	}

}

public class Pb10845 {
	
	public static void main(String[] args) throws IOException{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int cmdNum = Integer.parseInt(br.readLine());
		Queue pbQueue = new Queue(cmdNum);
		String[] cmd;
		
		while(cmdNum-->0) {
			cmd = br.readLine().split(" ");
			
			switch(cmd[0]) {
				case "push":
					pbQueue.push(Integer.parseInt(cmd[1]));
					break;
				case "pop":
					bw.write(String.valueOf(pbQueue.pop()));
					bw.write("\n");
					break;
				case "size":
					bw.write(String.valueOf(pbQueue.size()));
					bw.write("\n");
					break;
				case "empty":
					bw.write(String.valueOf(pbQueue.empty()));
					bw.write("\n");
					break;
				case "front":
					bw.write(String.valueOf(pbQueue.front()));
					bw.write("\n");
					break;
				case "back":
					bw.write(String.valueOf(pbQueue.back()));
					bw.write("\n");
					break;
			}
			
		}
		
		bw.flush();
		bw.close();
		br.close();
		
	}
}

 

결과

출력 방법1

bw.write(pbQueue.empty()+"\n");

 

출력 방법2

bw.write(String.valueOf(pbQueue.front()));
bw.write("\n");

 

=> 방법2로 출력하는 경우에 메모리와 시간이 줄어드는 것을 확인할 수 있다.

 

 

bw.write(pbQueue.empty());
bw.write("\n");

BufferedWriter 사용시 정수를 그대로 출력하려고 할 경우 오류가 발생한다. 

즉, BufferedWriter 사용하여 정수를 출력하는 경우 String으로 변환해야한다. 

 

 

'Coding Test > Baekjoon' 카테고리의 다른 글

[Baekjoon] 1406번: 에디터  (0) 2022.02.13
[Baekjoon] 10828번: 스택  (0) 2022.02.09