-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deque.cpp
100 lines (89 loc) · 2.17 KB
/
Deque.cpp
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
89
90
91
92
93
94
95
96
97
98
99
100
#include "Deque.hpp"
// Constructor
Deque::Deque() : front(nullptr), rear(nullptr), size(0) {}
// Destructor
Deque::~Deque() {
while (!isEmpty()) {
popFront();
}
}
// Check if the deque is empty
bool Deque::isEmpty() const {
return size == 0;
}
// Get the current size of the deque
int Deque::getSize() const {
return size;
}
// Add an element to the front of the deque
void Deque::pushFront(const std::string& data) {
Node* newNode = new Node(data);
if (isEmpty()) {
front = rear = newNode;
} else {
newNode->next = front;
front->prev = newNode;
front = newNode;
}
size++;
}
// Add an element to the rear of the deque
void Deque::pushRear(const std::string& data) {
Node* newNode = new Node(data);
if (isEmpty()) {
front = rear = newNode;
} else {
newNode->prev = rear;
rear->next = newNode;
rear = newNode;
}
size++;
}
// Remove and return an element from the front of the deque
std::string Deque::popFront() {
if (isEmpty()) {
throw std::runtime_error("Deque is empty");
}
Node* temp = front;
std::string value = front->data;
front = front->next;
if (front) {
front->prev = nullptr;
} else {
rear = nullptr;
}
delete temp;
size--;
return value;
}
// Remove and return an element from the rear of the deque
std::string Deque::popRear() {
if (isEmpty()) {
throw std::runtime_error("Deque is empty");
}
Node* temp = rear;
std::string value = rear->data;
rear = rear->prev;
if (rear) {
rear->next = nullptr;
} else {
front = nullptr;
}
delete temp;
size--;
return value;
}
// Get the element at the front of the deque
std::string Deque::getFront() const {
if (isEmpty()) {
throw std::runtime_error("Deque is empty");
}
return front->data;
}
// Get the element at the rear of the deque
std::string Deque::getRear() const {
if (isEmpty()) {
throw std::runtime_error("Deque is empty");
}
return rear->data;
}