Post

Stack

스택 구현하기 ==========

자료구조의 기본이라고 하면 스택가 있다 백준 10828번에서 마주친 스택

#include 헤더 파일을 쓰느 방법도 있지만 문제가 문제인지라 직접 구현을 해보기로했다.

# Class로 나의 스택 구현하기

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
  class myStack{
public:
    int current=-1;
    int stack[10001];
    
    void push(int num)
    {
        stack[++current] = num;
    }
    void pop(void)
    {
        if(current==-1)
        {
            cout << -1 <<endl;
        }
        else
        {
            cout << stack[current]<<endl;
            stack[current] = NULL;
            current--;
        }
    }
    void size(void)
    {
        cout << current+1 << endl;
    }
    void empty(void)
    {
        if(current == -1)
        {
            cout << 1 << endl;
        }
        else cout << 0 <<endl;
    }
    void top(void)
    {
        if(current ==-1)
        {
            cout << -1 << endl;
        }
        else
        {
            cout << stack[current] <<endl;
        }
    }
};

myStack 클래스에는 현재 위치를 저장하는 변수 current와 스택을 표현하는 배열 stack이 있다. 변수를 집어넣으면 현재위치가 늘어나고 아무것도 없을 땐 현재위치를 -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
  int main() {
    int order;
    cin >> order;
    
    myStack s1;
    for(int i=0;i<order;i++)
    {
        string str;
        cin >> str;
        
        if(str == "push")
        {
            int num;
            cin >> num;
            
            s1.push(num);
        }
        else if(str == "pop")
        {
            s1.pop();
        }
        else if(str == "size")
        {
            s1.size();
        }
        else if(str == "empty")
        {
            s1.empty();
        }
        else if(str == "top")
        {
            s1.top();
        }
    }
}

문자열을 string변수에 입력받아서 비교하고 각 경우마다 함수를 호출하는 식으로 구현하였다. 다음에는 큐도 구현해봐야징

This post is licensed under CC BY 4.0 by the author.