백준 실버Lv4 10828 스택

weonest·2023년 4월 21일
0

coding-test

목록 보기
22/36

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

  • push X: 정수 X를 스택에 넣는 연산이다.
  • pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 스택에 들어있는 정수의 개수를 출력한다.
  • empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
  • top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.


나의 풀이

오랜만에 프로그래머스 문제가 아닌 백준 문제를 풀어보았다. 입출력을 대신 진행해주는 프로그래머스만 쓰다보니 후에 입출력을 스스로 해야하는 문제를 맞이했을 때 우왕좌왕할까봐 ㅋㅋ..

문제 자체는 어렵지 않은 문제였다. 명령에 해당하는 메서드나 알고리즘을 구현해 둔 후에 명령이 들어올때마다 실행 → 출력만 해주면 되는 문제였기 때문이다.

내가 푼 풀이는 다음과 같다

public class Main {

    public static void main(String[] args) throws IOException {
        int sum = 0;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < N; i++) {
            String[] command = br.readLine().split(" ");

            switch (command[0]) {
                case "push":
                    push(stack, Integer.parseInt(command[1]));
                    break;
                case "pop":
                    System.out.println(pop(stack));
                    break;
                case "size":
                    System.out.println(size(stack));
                    break;
                case "empty":
                    System.out.println(empty(stack));
                    break;
                case "top":
                    System.out.println(top(stack));
                    break;
            }

        }
    }

    public static void push(Stack<Integer> stack, int n) {
        stack.push(n);
    }

    public static int pop(Stack<Integer> stack) {
        int n = -1;
        if (!stack.isEmpty()) {
            n = stack.pop();
        }
        return n;
    }

    public static int size(Stack<Integer> stack) {
        int n = 0;
        if (!stack.isEmpty()) n = stack.size();
        return n;
    }

    public static int empty(Stack<Integer> stack) {
        int n = 0;
        if (stack.isEmpty()) n = 1;
        return n;
    }

    public static int top(Stack<Integer> stack) {
        int n = -1;
        if (!stack.isEmpty()) {
            n = stack.peek();
        }
        return n;
    }
}

switch문을 통해 입력받은 명령어에 해당하는 메서드를 탈 수 있게끔 만들어주었다. 명령어에서 push 명령어 같은 경우 push 1과 같이 공백을 두고 입력할 숫자가 들오기 때문에 모든 명령어를 배열에 담아 처리를 해주었다.

switch를 쓰지 않고 직접 처리하는 방법은 다음과 같다.

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int n = Integer.parseInt(br.readLine());

        // Stack 객체 생성.
		Stack<Integer> stack = new Stack<>();

        // 동일.
		for(int i = 0;i<n;i++) {
			String cons = br.readLine();

			if(cons.contains("push")) { // 동일.
				String spt[] = cons.split(" ");
				stack.push(Integer.parseInt(spt[1]));
			}else if(cons.contains("pop")) { // 동일.
				if(stack.empty()) bw.write(-1+"\n"); // 별도의 empty() 체크가 필요하다.
				else bw.write(stack.pop()+"\n");
			}else if(cons.contains("size")) { // 동일.
				bw.write(stack.size()+"\n");
			}else if(cons.contains("empty")) { // 동일.
				if(stack.empty()) bw.write(1+"\n"); // 별도의 empty() 체크가 필요하다.
				else bw.write(0+"\n");
			}else if(cons.contains("top")) { // 동일.
				if(stack.empty())bw.write(-1+"\n");	// 별도의 empty() 체크가 필요하다.
				else bw.write(stack.peek()+"\n");
			}
		}

		bw.flush();
		bw.close();
		br.close();

	}

}

출력을 BufferedWirter로 해주며 따로 메서드를 생성하지 않았기에 코드가 좀 더 간결해보인다

0개의 댓글