본문 바로가기

알고리즘/큐

10866번 큐

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_front".equals(command)){
					String tempInput=st.nextToken();
					int input=Integer.parseInt(tempInput);
					push_front(input);
				}else if("push_back".equals(command)){
					String tempInput=st.nextToken();
					int input=Integer.parseInt(tempInput);
					push_back(input);
				}else if("pop_back".equals(command)){
					sf.append(pop_back() +"\n");
				}else if("pop_front".equals(command)){
					sf.append(pop_front() +"\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_back(int input){
		queue[index]=input;
		index++;
	}
	
	public static void push_front(int input){
		for(int i=index;i>0;i--){
			queue[i]=queue[i-1];
		}
		queue[0]=input;
		index++;
	}
	
	public static int pop_front(){
		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 pop_back(){
		int output=-1;
		if(index>0){
			output=queue[index-1];
			index--;
		}
		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;
	}

}

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

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