본문 바로가기
스터디/자료구조

[ 자료구조 ] Stack

by 알 수 없는 사용자 2020. 2. 21.

스택(Stack)은 후입선출(Last In First Out) 의 형태를 띄는 자료구조로 나중에 들어온 데이터가 먼저 나갑니다.

 

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
#include <iostream>
#define MAXSIZE 100
 
using namespace std;
 
template<typename T>
class Stack
{
public:
    int top;
    int size;
    T* values;
 
    Stack()
    {
        size = MAXSIZE;
        values = new T[size];
        top = -1;
    }
 
    ~Stack()
    {
        delete[] values;
    }
 
    void push(T value)
    {
        if (!isFull())
            values[++top] = value;
        else
            cout << "Stack is Full" << endl;
    }
 
    void pop()
    {
        if (!empty())
            top--;
        else
            cout << "Stack is Empty" << endl;
    }
 
    T Top()
    {
        if (!empty())
            return values[top];
        else
            return NULL;
    }
 
    bool empty()
    {
        if (top < 0)
            return true;
        else
            return false;
    }
 
    bool isFull()
    {
        if (top + 1 == size)
            return true;
        else
            return false;
    }
};
 

 

2. STL 활용

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
#include <iostream>
#include <stack>
 
using namespace std;
 
int main()
{
    stack<int> st;
 
    // push
    st.push(3);
    st.push(2);
    st.push(1);
 
    // pop
    st.pop();
 
    // top
    cout << "top : " << st.top() << endl;
 
    // size
    cout << "size : "<< st.size() << endl;
 
    // empty
    cout << "empty : " << st.empty() << endl;
 
    return 0;
}
 

 

'스터디 > 자료구조' 카테고리의 다른 글

[ 자료구조 ] Bubble Sort  (0) 2020.02.23
[ 자료구조 ] Selection Sort  (0) 2020.02.23
[ 자료구조 ] Binary Search Tree  (0) 2020.02.23
[ 자료구조 ] Deque  (0) 2020.02.22
[ 자료구조 ] Queue  (0) 2020.02.21