스택(Stack) 구현

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
84
85
86
#include <iostream>
using namespace std;
 
class stack
{
public:
    int max;
    int* arr;
    int top;
    void setmax(int num)
    {
        max = num;
    };
 
    void push(int num) {
        if (isFull()) {
            cout << "꽉 참"<<"\n";
            return ;
        }
        arr[top++= num;
    };
 
    void print() {
        if (isEmpty()) {
            cout << "비어있음\n";
            return;
        }
        for (int i = 0; i < top; i++) {
            cout << i + 1 << "번째 값은 : " << arr[i] << "\n";
        }
    }
 
    int pop() {
        if (isEmpty()) {
            cout << "비어있음\n";
            return -1;
        }
        cout << "pop : " << arr[--top] << "\n";
        return arr[top];
    }
 
    bool isEmpty() {
        if (top == 0) {
            return true;
        }
        else {
            return false;
        }
    }
 
    bool isFull() {
        if (top == max) {
            return true;
        }
        else {
            return false;
        }
    }
};
 
stack create(int num) {
    int *arrt = new int[num]; //동적 배열 생성
    stack stk;
    stk.setmax(num);
    stk.arr = arrt;
    stk.top = 0;
    return stk;
}
 
int main() {
    stack stk = create(5); //5 크기의 스택 생성
    stk.push(10);
    stk.push(13);
    stk.push(1);
    stk.push(18);
    stk.push(20);
    stk.push(2); //예외 발생
    stk.print();
    stk.pop();
    stk.pop();
    stk.pop();
    stk.pop();
    stk.pop();
    stk.pop(); //예외 발생
}
 
cs

실행 결과