본문 바로가기

알고리즘/큐

10845번 큐

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


public class Main {
	static  int queue[]=new int[10001];
	static int index=0;
	public static void main(String[] args) {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
		StringBuffer sf=new StringBuffer();
		try {
			String tempTestCase=br.readLine();
			int testCase=Integer.parseInt(tempTestCase);
			sf.setLength(0);
			for(int i=0;i<testCase;i++){
				String tempCommand=br.readLine();
				StringTokenizer st=new StringTokenizer(tempCommand);
				String command=st.nextToken();
				if("push".equals(command)){
					String tempInput=st.nextToken();
					int input=Integer.parseInt(tempInput);
					push(input);
				}else if("pop".equals(command)){
					sf.append(pop() +"\n");
				}else if("size".equals(command)){
					sf.append(size()+"\n");
				}else if("empty".equals(command)){
					sf.append(empty()+"\n");
				}else if("front".equals(command)){
					sf.append(front()+"\n");
				}else if("back".equals(command)){
					sf.append(back()+"\n");
				}
			}
			bw.write(sf.toString());
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}	
	public static void push(int input){
		queue[index]=input;
		index++;
	}
	
	public static int pop(){
		int output=-1;
		if(index>0){
			output=queue[0];
			index--;
			for(int i=0;i<index;i++){
				queue[i]=queue[i+1];
			}
		}
		return output;
	}
	
	public static int size(){
		return index;
	}
	
	public static int empty(){
		int result=1;
		if(index>0){
			result=0;
		}
		return result;
	}
	
	public static int front(){
		int result=-1;
		if(index>0){
			result=queue[0];
		}
		return result;
	}
	
	public static int back(){
		int result=-1;
		if(index>0){
			result=queue[index-1];
		}
		return result;
	}

}

'알고리즘 > ' 카테고리의 다른 글

10866번 큐  (0) 2020.06.30
1158번 요세푸스 문제  (0) 2020.06.30