BOJ 10845 큐

1 개요[ | ]

  • 큐의 개념을 익히고 실습해 봅니다
  • 알고리즘 분류: 큐

2 Java[ | ]

import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;
public class Main {
	static Deque<Integer> queue;
	static void excuteLine(String line) {
	    //System.out.println( queue );
	    //System.out.println( line );
	    String[] arr = line.split(" ");
	    String command = arr[0];
	    int num = 0;
	    if( arr.length > 1 ) num = Integer.parseInt(arr[1]);
		switch( command ) {
		case "push":
			queue.add( num );
			return;
		case "pop":
			if( queue.isEmpty() ) System.out.println(-1);
			else System.out.println( queue.poll() );
			return;
		case "size":
			System.out.println( queue.size() );
			return;
		case "empty":
			if( queue.isEmpty() ) System.out.println(1);
			else System.out.println(0);
			return;
		case "front":
			if( queue.isEmpty() ) System.out.println(-1);
			else System.out.println( queue.peek() );
			return;
		case "back":
			if( queue.isEmpty() ) System.out.println(-1);
			else System.out.println( queue.getLast() );
			return;
		}
	}
	public static void main(String args[]) {
		queue = new ArrayDeque<Integer>();
		Scanner sc = new Scanner(System.in);
		int n = Integer.parseInt(sc.nextLine());
		for(int i=0; i<n; i++) excuteLine( sc.nextLine() );
	}
}

3 Perl[ | ]

$n = <>;
@queue = ();
for (1..$n) {
    ($m, $o) = (split / +/, <>);
    chomp $m; chomp $o;
    push @queue, $o if ($m eq "push");
    if ($m eq "pop") {
       $pop = shift @queue;
       if (!$pop) {
           printf("-1\n");
       } else {
           printf("%d\n", $pop);
       }
    }
    printf("%d\n", ~~@queue) if ($m eq "size");
    printf("%d\n", @queue?"0":"1") if ($m eq "empty");
    if ($m eq "front") {
       $front = $queue[0];
       if (!$front) {
           printf("-1\n")
       } else {
           printf("%d\n", $front);
       }
    }
    if ($m eq "back") {
       $back = $queue[-1];
       if (!$back) {
          printf("-1\n");
       } else {
          printf("%d\n", $back);
       }
    }
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}