Skip to content

Commit 9a3421f

Browse files
committed
Implement stack using linked list
1 parent 511f9fd commit 9a3421f

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

include/ds/stack.hpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#pragma once
2+
#ifndef DS_STACK_HPP
3+
#define DS_STACK_HPP
4+
5+
#include <cstddef>
6+
#include <stdexcept>
7+
#include <utility>
8+
9+
namespace ds {
10+
11+
template <typename value_t>
12+
class stack_t {
13+
private:
14+
struct node_t {
15+
value_t value;
16+
node_t* next;
17+
18+
template <typename... args_t>
19+
node_t(node_t* next_node, args_t&&... args)
20+
: value(std::forward<args_t>(args)...)
21+
, next(next_node) {}
22+
};
23+
24+
node_t* head = nullptr;
25+
std::size_t size = 0;
26+
27+
public:
28+
stack_t() = default;
29+
30+
~stack_t() {
31+
while (head) {
32+
auto* next = head->next;
33+
delete head;
34+
head = next;
35+
}
36+
}
37+
38+
template <typename... args_t>
39+
void push(args_t&&... args) {
40+
head = new node_t(head, std::forward<args_t>(args)...);
41+
++size;
42+
}
43+
44+
void pop() {
45+
if (empty()) {
46+
throw std::runtime_error("stack is empty");
47+
}
48+
auto* next = head->next;
49+
delete head;
50+
head = next;
51+
--size;
52+
}
53+
54+
value_t& top() {
55+
if (empty()) {
56+
throw std::runtime_error("stack is empty");
57+
}
58+
return head->value;
59+
}
60+
61+
const value_t& top() const {
62+
if (empty()) {
63+
throw std::runtime_error("stack is empty");
64+
}
65+
return head->value;
66+
}
67+
68+
bool empty() const noexcept { return size == 0; }
69+
70+
std::size_t get_size() const noexcept { return size; }
71+
};
72+
73+
} // namespace ds
74+
75+
#endif // !DS_STACK_HPP

0 commit comments

Comments
 (0)