[백준][10828번] 스택

Updated:

내가푼 코드

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Stack st = new Stack();

        while(n-- >0){
            String cmd = sc.next();
            if(cmd.equals("push")){
                int num = sc.nextInt();
                st.push(num);
            }else if(cmd.equals("top")){
                System.out.println(st.top());
            }else if(cmd.equals("size")){
                System.out.println(st.size());
            }else if(cmd.equals("empty")){
                if(st.empty()){
                    System.out.println("1");
                }
                else{
                    System.out.println("0");
                }
            }else if(cmd.equals("pop")){
                int num = st.pop();
                System.out.println(num);
            }
        }
    }

    public static class Stack{
        private int data[] = new int[10000];
        private int size=0;

        public void push(int x){
            data[size++] = x;
        }

        public boolean empty(){
            if(size == 0) return true;
            else return false;
        }

        public int pop(){
            if(empty()) return -1;
            else{
                size--;
                return data[size];
            }
        }

        public int size(){
            return size;
        }

        public int top(){
            if(empty()) return -1;
            return data[size-1];
        }
    }
}

다른 풀이

import java.util.*;
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("size")) {
                System.out.println(size);
            } else if (cmd.equals("empty")) {
                if (size == 0) {
                    System.out.println("1");
                } else {
                    System.out.println("0");
                }
            } else if (cmd.equals("pop")) {
                if (size == 0) {
                    System.out.println("-1");
                } else {
                    System.out.println(stack[size-1]);
                    size -= 1;
                }
            }
        }
    }
}

Leave a comment