-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly-linked-list-deque.cpp
161 lines (138 loc) · 2.8 KB
/
Doubly-linked-list-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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// main.cpp
// P&D 10: Double linked list deque
//
// Created by Julia Vister on 26/05/2022.
//
#include <iostream>
#include <stdexcept>
struct Node{
int value;
Node *next;
Node *prev;
Node(int value):
value(value),
next(nullptr),
prev(nullptr){}
};
class Deque{
Node *head;
Node *tail;
public:
Deque():
head(nullptr), //constructor
tail(nullptr){}
Deque(const Deque& original):head(nullptr),tail(nullptr){ //copy constructor
/* if(!original.empty()){
head=new Node(original.head->value);
Node *source =original.head->next;
Node *destination=head;
while(source!=nullptr){
destination->next=new Node(source->value);
destination=destination->next;
source=source->next;
}
tail=destination;
} */
Node *tmp = original.head;
while (tmp != nullptr) {
push_front(tmp->value);
tmp = tmp -> next;
}
}
Deque &operator=(Deque cpy){ //assignment operator
std::swap(cpy.head, head);
std::swap(cpy.tail, tail);
return *this;
}
bool empty()const{
return (head==nullptr);
}
int back(){
if(empty()){
throw std::runtime_error("empty deque");
}
return tail->value;
}
int front(){
if(empty()){
throw std::runtime_error("empty deque");
}
return head->value;
}
void push_front(int x){
if(empty()){
head=new Node(x);
tail=head;
}
else{
Node *tmp=new Node(x);
tmp->next = head;
head->prev=tmp;
head=tmp;
}
}
void push_back(int x){
if(empty()){
head=new Node(x);
tail=head;
}
else{
Node *tmp=new Node(x);
tmp->prev=tail;
tail->next=tmp;
tail=tmp;
}
}
void pop_back(){
if(empty()){
throw std::runtime_error("empty deque");
}
if(head==tail){
delete head;
head=nullptr;
tail=nullptr;
}
else{
tail=tail->prev;
delete tail->next;
tail->next=nullptr;
}
}
void pop_front(){
if(empty()){
}
if(head==tail){
delete head;
head=nullptr;
tail=nullptr;
}
else{
head=head->next;
delete head->prev;
head->prev=nullptr;
}
}
void clear(){
while(!empty()){
pop_front();
}
}
~Deque(){
clear();
}
};
int main() {
Deque d;
d.push_front(2);
d.push_back(4);
std::cout<< d.back() << " ";
std::cout << d.front() << " ";
d.push_back(8);
d.push_front(6);
std::cout << d.front() << " ";
d.push_back(10);
std::cout << d.front() << " ";
d.pop_front();
puts("");
return 0;
}