PS, 언어 공부/알고리즘 문제풀이

[JAVA] 백준 온라인 저지 10828

Emil :) 2020. 6. 25. 19:02
728x90
반응형

문제


코드


Stack을 import하지 말고 풀기와 하고 풀기 둘 다 해봤다.
뭐 어차피 평소엔 Stack import해서 쓰는데 복습할 겸..

Stack import X

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] stack = new int[n];
        int size = 0;
        while(n-- > 0){
            String cmd = sc.next();
            if(cmd.equals("push")){
                int num = Integer.parseInt(sc.next());
                stack[size++] = num;
            } else if(cmd.equals("top")){
                if(size == 0){
                    System.out.println("-1");
                } else {
                    System.out.println(stack[size-1]);
                }
            } else if(cmd.equals("pop")){
                if(size == 0){
                    System.out.println("-1");
                } else {
                    System.out.println(stack[size-1]);
                    size-=1;
                }
            } else if(cmd.equals("size")){
                System.out.println(size);
            } else if(cmd.equals("empty")){
                if(size == 0){
                    System.out.println("1");
                } else {
                    System.out.println("0");
                }
            }
        }
    }
}

 

Stack import O

package java_practice;
import java.util.*;

public class boj_10828 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Stack<Integer> stack = new Stack<Integer>();
        for (int k = 0; k < n; k++){
            String cmd = sc.next();
            if(cmd.equals("push")){
                int num = Integer.parseInt(sc.next());
                stack.push(num);
            } else if(cmd.equals("top")){
                if(stack.empty()){
                    System.out.println("-1");
                } else {
                    System.out.println(stack.peek());
                }
            } else if(cmd.equals("size"))
                System.out.println(stack.size());
              else if(cmd.equals("empty")){
                if(stack.empty())
                    System.out.println("1");
                else
                    System.out.println("0");
            } else if(cmd.equals("pop")){
                if(stack.empty())
                    System.out.println("-1");
                else
                    System.out.println(stack.pop());
            }
        }
        sc.close();
    }
}

 

결과


기본이라 딱히 설명할게 없다.

728x90
반응형