summaryrefslogtreecommitdiff
path: root/Year_1/Programming_2/data_structures/stack.cc
blob: ffff7806a909bf3859d9be4399f36d7504b6df8f (plain)
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
#include<iostream>

using namespace std;

template<typename T>
struct node {
    T value;
    node<T>* next;
};

template<class T>
class stack {
public:
    stack() : _head{nullptr} {}

    ~stack() {
        auto iter = _head;
        while(iter) {
            delete iter;
            iter = iter->next;
        }
    }

    stack<T>* push(T val) {

        if(!_head) {
            _head = new node<T>{val, nullptr};
        } else {
            _head = new node<T>{val, _head};
        }

        return this;
    }

    node<T>* pop() {
        if(!_head) return nullptr;
        node<T>* elem = _head;
        delete _head;
        _head = elem->next;

        return elem;
    }

    void print() {
        auto iter = _head;
        while(iter) {
            cout << iter->value << ' ';
            iter = iter->next;
        }
        cout << endl;
    }
private:
    node<T>* _head;
};

int main() {
    stack<int>* s = new stack<int>();

    s->pop();
    s->push(4)->push(2)->push(8);
    s->print();
    auto e = s->pop();
    if(e)
        cout << e->value << endl;
    s->push(1);
    s->print();

    delete s;
    return 0;
}