summaryrefslogtreecommitdiff
path: root/graphs/cpp/doubly_linked_list/list.cc
blob: 36cf5ad6bc03041b176e9e62ae78815003d443e2 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "list.hh"
List::List()
    : nb_elts_{ 0 }
{}
void List::push_front(int i)
{
    nb_elts_++;
    if (nb_elts_ == 1)
    {
        first_ = std::make_shared<Node>(i);
        last_ = first_;
        return;
    }
    std::shared_ptr<Node> ns = std::make_shared<Node>(i);
    ns->set_next(first_);
    first_->set_prev(ns);
    first_ = ns;
}
std::optional<int> List::pop_front()
{
    if (nb_elts_ == 0)
    {
        return std::nullopt;
    }
    nb_elts_--;
    int res = first_->get_val();
    if (nb_elts_ == 0)
    {
        first_ = nullptr;
        last_ = nullptr;
        return res;
    }
    std::shared_ptr<Node> tmp = first_->get_next();
    first_->set_next(nullptr);
    tmp->set_prev(nullptr);
    first_ = tmp;
    return res;
}
void List::push_back(int i)
{
    nb_elts_++;
    if (nb_elts_ == 1)
    {
        first_ = std::make_shared<Node>(i);
        last_ = first_;
        return;
    }
    std::shared_ptr<Node> ns = std::make_shared<Node>(i);
    ns->set_prev(last_);
    last_->set_next(ns);
    last_ = ns;
}
std::optional<int> List::pop_back()
{
    if (nb_elts_ == 0)
    {
        return std::nullopt;
    }
    nb_elts_--;
    int res = last_->get_val();
    if (nb_elts_ == 0)
    {
        first_ = nullptr;
        last_ = nullptr;
        return res;
    }
    std::shared_ptr<Node> tmp = last_->get_prev();
    last_->set_prev(nullptr);
    tmp->set_next(nullptr);
    last_ = tmp;
    return res;
}
void List::print(std::ostream& os) const
{
    if (nb_elts_ == 0)
        return;
    os << first_->get_val();
    for (Node* node = first_->get_next().get(); node;
         node = node->get_next().get())
    {
        os << " " << node->get_val();
    }
    // os << "\n";
}
size_t List::length() const
{
    return nb_elts_;
}