🤔스택

🔑스택 구현

스택은 위로 쌓는 방식이라서 top이라는 인덱스를 만들어 구현해볼 수 있습니다. 배열의 인덱스는 0부터 시작이므로 top을 -1로 초기화해줍니다.

1
2
3
4
5
6
7
const int STACK_SIZE = 10;

struct Stack
{
    int container[STACK_SIZE]{};
    int topIndex = -1;
};

정수를 스택에 넣고자(Push) 한다면 top 인덱스를 하나 증가시킨 곳에 해당 정수를 스택 배열에 넣어주면 됩니다.

정수를 스택에서 빼려고(Pop) 한다면 스택 배열에서 top 인덱스를 하나 감소시켜주면 됩니다.

스택이 비어있는지 확인하는 방법은 top 인덱스가 0보다 작을 때는 원소가 하나도 없는 상태이므로 비어있는 것이고 top 인덱스가 0보다 크거나 같은 숫자일 때는 비어있지 않은 상태입니다.

스택에 원소를 넣으면 top인덱스가 증가하므로 top 인덱스 자체가 스택의 사이즈가 됩니다. 하지만 top이 처음에 -1로 초기화되어 스택의 사이즈가 음수가 될 수는 없으므로 top 인덱스에 1을 더해줍니다.



🔑전체 소스 코드

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <string>
 
const int STACK_SIZE = 10000;
 
struct Stack
{
    int container[STACK_SIZE]{};
    int topIndex = -1;
};
 
void UserInput(Stack& stack, std::string temp);
void Push(Stack& stack, int n);
void Pop(Stack& stack);
void Size(Stack& stack);
void Empty(Stack& stack);
void Top(Stack& stack);
 
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    
    Stack myStack;   
    int n;
 
    std::cin >> n;
 
    for(int i = 0; i < n; i++)
    {
        std::string temp;
 
        std::cin >> temp;
        
        UserInput(myStack, temp);
    }
}
 
void UserInput(Stack& stack, std::string temp)
{
    if(temp == "push")
    {
        int value;
        std::cin >> value;
 
        Push(stack, value);
    }
    else if(temp == "pop")
    {
        Pop(stack);
    }
    else if(temp == "size")
    {
        Size(stack);
    }
    else if(temp == "empty")
    {
        Empty(stack);
    }
    else if(temp == "top")
    {
        Top(stack);
    }
    else
    {
        return;
    }
}
 
void Push(Stack& stack, int n)
{
    if(stack.topIndex >= STACK_SIZE - 1)
    {
        return;
    }
 
    stack.container[++stack.topIndex] = n;
}
 
void Pop(Stack& stack)
{
    if(stack.topIndex < 0)
    {
        std::cout << -1 << '\n';
        return;
    }
 
    std::cout << stack.container[stack.topIndex--] << '\n';
}
 
void Size(Stack& stack)
{
    std::cout << stack.topIndex + 1 << '\n';
}
 
void Empty(Stack& stack)
{
    if(stack.topIndex < 0)
    {
        std::cout << 1 << '\n';
    }
    else
    {
        std::cout << 0 << '\n';
    }
}
 
void Top(Stack& stack)
{
    if(stack.topIndex < 0)
    {
        std::cout << -1 << '\n';
        return;
    }
 
    std::cout << stack.container[stack.topIndex] << '\n';
}



Leave a comment