Home 10828번(스택)
Post
Cancel

10828번(스택)

첫 시도

  • 스택은 다음을 사용하여 구현할 수 있다.
    1. 배열
    2. 리스트
  • 배열을 이용하여 구현하였다.

해결

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;

public class Main {
    public static void main(String[] ars) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int N = Integer.parseInt(br.readLine());
        Stack st = new Stack(N);

        for (int i = 0; i < N; i++) {
            String[] input = br.readLine().split(" ");
            String commend = input[0];
            switch (commend){
                case "push":
                    int num = Integer.parseInt(input[1]);
                    st.push(num);
                    break;
                case "pop":
                    sb.append(st.pop()).append("\n");
                    break;
                case "size":
                    sb.append(st.size()).append("\n");
                    break;
                case "empty":
                    sb.append(st.empty()).append("\n");
                    break;
                case "top":
                    sb.append(st.top()).append("\n");
                    break;
            }
        }
        System.out.println(sb.toString());


    }

}
class Stack{
    int top;
    int[] arr;

    public Stack(int size) {
        this.top = -1;
        this.arr = new int[size];
    }

    public boolean push(int input){
        arr[++top] = input;
        return true;
    }

    public int pop(){
        int temp = -1;
        if(!(top == -1)){
            temp = arr[top];
            arr[top--] = 0;
        }
        return temp;
    }

    public int size(){
        return top+1;
    }

    public int empty(){
        int temp = 1;
        if(!(top == -1)){
            temp = 0;
        }
        return temp;
    }

    public int top(){
        int temp = -1;
        if(!(top == -1)){
            temp = arr[top];
        }
        return temp;
    }
}

참고

  • 직접구현
This post is licensed under CC BY 4.0 by the author.