Skip to content

Commit 97a20ea

Browse files
committed
fix: stack and queue
1 parent 901959d commit 97a20ea

5 files changed

Lines changed: 152 additions & 0 deletions

File tree

510 KB
Loading
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# Stack and queue
2+
3+
!!! warning
4+
5+
This section is a continuation of the [Dynamic Data](../03-dynamic-data/README.md) section. Please make sure to read it before continuing.
6+
7+
## Stack
8+
9+
![img_1.png](img_1.png)[source](https://programmerhumor.io/stackoverflow-memes/data-structures-in-a-nutshell/)
10+
11+
Stacks are a type of dynamic data where the last element added is the first one to be removed. This is known as LIFO (Last In First Out) or FILO (First In Last Out). Stacks are used in many algorithms and data structures, such as the depth-first search algorithm, back-track and the call stack.
12+
13+
### Stack Basic Operations
14+
15+
- `push` - Add an element to the top of the stack.
16+
- `pop` - Remove the top element from the stack.
17+
- `top` - Return the top element of the stack.
18+
19+
![stack.gif](stack.gif) [source](https://medium.com/@joshalphonse/stacks-queues-97037b3c01c6)
20+
21+
### Stack Implementation
22+
23+
You can either implement it using a dynamic array or a linked list. But the dynamic array implementation is more efficient in terms of memory and speed. So let's use it.
24+
25+
```c++
26+
#include <iostream>
27+
28+
// stack
29+
template <typename T>
30+
class Stack {
31+
T* data; // dynamic array
32+
size_t size; // number of elements in the stack
33+
size_t capacity; // capacity of the stack
34+
public:
35+
Stack() : data(nullptr), size(0), capacity(0) {}
36+
~Stack() {
37+
delete[] data;
38+
}
39+
void push(const T& value) {
40+
// if it needs to be resized
41+
// amortized cost of push is O(1)
42+
if (size == capacity) {
43+
capacity = capacity == 0 ? 1 : capacity * 2;
44+
T* new_data = new T[capacity];
45+
std::copy(data, data + size, new_data);
46+
delete[] data;
47+
data = new_data;
48+
}
49+
// stores the value and then increments the size
50+
data[size++] = value;
51+
}
52+
T pop() {
53+
if (size == 0)
54+
throw std::out_of_range("Stack is empty");
55+
56+
// shrink the array if necessary
57+
// ammortized cost of pop is O(1)
58+
if (size <= capacity / 4) {
59+
capacity /= 2;
60+
T* new_data = new T[capacity];
61+
std::copy(data, data + size, new_data);
62+
delete[] data;
63+
data = new_data;
64+
}
65+
return data[--size];
66+
}
67+
T& top() const {
68+
if (size == 0)
69+
throw std::out_of_range("Stack is empty");
70+
// cost of top is O(1)
71+
return data[size - 1];
72+
}
73+
size_t get_size() const {
74+
return size;
75+
}
76+
bool is_empty() const {
77+
return size == 0;
78+
}
79+
};
80+
```
81+
82+
## Queue
83+
84+
![Queue.gif](Queue.gif) [source](https://embetronicx.com/tutorials/p_language/c/queue-in-c/)
85+
86+
A queue is a type of dynamic data where the first element added is the first one to be removed. This is known as FIFO (First In First Out). Queues are used in many algorithms and data structures, such as the breadth-first search algorithm. Usually it is implemented as a linked list, in order to provide O(1) time complexity for the `enqueue` and `dequeue` operations. But it can be implemented using a dynamic array as well and amortize the cost for resizing. The dynamic array implementation is more efficient in terms of memory and speed(if not resized frequently).
87+
88+
### Queue Basic Operations
89+
90+
- `enqueue` - Add an element to the end of the queue.
91+
- `dequeue` - Remove the first element from the queue.
92+
- `front` - Return the first element of the queue.
93+
94+
![queue-operations.gif](queue-operations.gif)[source](https://algo.aspires.cc/fundamental/ch1-linear-structure)
95+
96+
### Queue Implementation
97+
98+
```c++
99+
// queue
100+
template <typename T>
101+
class Queue {
102+
// dynamic array approach instead of linked list
103+
T* data;
104+
size_t front; // index of the first valid element
105+
size_t back; // index of the next free slot
106+
size_t capacity; // current capacity of the array
107+
size_t size; // number of elements in the queue
108+
109+
explicit Queue() : data(nullptr), front(0), back(0), capacity(capacity), size(0) {};
110+
111+
void enqueue(T value) {
112+
// resize if necessary
113+
// amortized O(1) time complexity
114+
if (size == capacity) {
115+
auto old_capacity = capacity;
116+
capacity = capacity ? capacity * 2 : 1;
117+
T* new_data = new T[capacity];
118+
for (size_t i = 0; i < size; i++)
119+
new_data[i] = data[(front + i) % old_capacity];
120+
delete[] data;
121+
data = new_data;
122+
front = 0;
123+
back = size;
124+
}
125+
data[back] = value;
126+
back = (back + 1) % capacity;
127+
size++;
128+
}
129+
130+
void dequeue() {
131+
if (size) {
132+
front = (front + 1) % capacity;
133+
size--;
134+
}
135+
// shrink if necessary
136+
if(size <= capacity / 4) {
137+
auto old_capacity = capacity;
138+
capacity /= 2;
139+
T* new_data = new T[capacity];
140+
for (size_t i = 0; i < size; i++)
141+
new_data[i] = data[(front + i) % old_capacity];
142+
delete[] data;
143+
data = new_data;
144+
front = 0;
145+
back = size;
146+
}
147+
}
148+
149+
T& head() {
150+
return data[front];
151+
}
152+
};
280 KB
Loading
112 KB
Loading
1.39 MB
Loading

0 commit comments

Comments
 (0)