somdaa / algorithmstudy

0 stars 0 forks source link

week-02. Queue-queue #5

Open ewqsaz123 opened 6 years ago

ewqsaz123 commented 6 years ago

https://www.acmicpc.net/problem/10845

levi-yo commented 6 years ago

import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner;

public class Queue_1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Deque q=new LinkedList<>();
    ArrayList list=new ArrayList<>();
    Scanner s=new Scanner(System.in);
    int n=Integer.parseInt(s.nextLine());
    for(int i=0;i<n;i++){
        String str=s.nextLine();
        if(str.contains("push")){
            String[] sArr=str.split(" ");
            q.offer(sArr[1]);
        }else if(str.contains("pop") && !q.isEmpty()){
            list.add(q.poll());
        }else if(str.contains("pop") && q.isEmpty()){
            list.add(-1);
        }else if(str.contains("size")){
            list.add(q.size());
        }else if(str.contains("empty")){
            list.add(q.isEmpty()?1:0);
        }else if(str.contains("front")){
            list.add(q.isEmpty()?-1:q.getFirst());
        }else if(str.contains("back")){
            list.add(q.isEmpty()?-1:q.getLast());
        }
    }
    Iterator it=list.iterator();
    while(it.hasNext()) System.out.println(it.next());
}

}

ewqsaz123 commented 6 years ago

import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack;

public class Solution_10845 {

/*
 * 알고리즘 분류. 큐
 */

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Queue<Integer> q = new LinkedList<>();

    for(int i=0; i<n; i++) {
        String s = sc.next();
        switch (s) {
        case "push":
            int x = sc.nextInt();
            q.offer(x);
            break;

        case "pop":
            if(q.isEmpty()) System.out.println(-1);
            else System.out.println(q.poll());
            break;
        case "size":
            System.out.println(q.size());
            break;
        case "empty":
            if(q.isEmpty()) System.out.println(1);
            else System.out.println(0);
            break;
        case "front":
            if(q.isEmpty()) System.out.println(-1);
            else System.out.println(q.peek());
            break;
        case "back":
            if(q.isEmpty()) System.out.println(-1);
            else {
                Stack<Integer> st = new Stack<>();
                st.addAll(q);
                System.out.println(st.peek());
            }
            break;

        default:
            break;
        }
    }
}

}