-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue_by_LinkedList.cpp
140 lines (118 loc) · 2.87 KB
/
queue_by_LinkedList.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
#include <iostream>
using namespace std;
template<typename T>
struct Node{
T data;
Node<T> *next = NULL;
Node<T> *prev = NULL;
};
template<typename T>
class LinkedList{
private:
int size;
Node<T> *head, *tail;
public:
LinkedList(){
size = 0;
head = tail = NULL;
}
bool isEmpty(){return (size == 0);}
void add(T data, int idx){
if (size < idx){
cout << "Index error\n";
return;
}
Node<T> *newNode = new Node<T>();
newNode->data = data;
if (isEmpty()) head = tail = newNode;
else if (idx == 0){
head->prev = newNode;
newNode->next = head;
head = newNode;
}
else if (idx == size){
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
else{
Node<T> *temp;
for (int i = 0; i < idx; i++) temp = temp->next;
temp->prev->next = newNode;
temp->next->prev = newNode;
}
size++;
}
T pop(int idx){
if (size <= idx) cout << "Index error\n";
else{
Node<T> *temp;
if (idx == 0){
if (size == 1) head = tail = NULL;
else{
temp = head;
head = head->next;
head->prev = NULL;
}
}
else if (idx == size - 1){
temp = tail;
tail = tail->prev;
tail->next = NULL;
}
else{
temp = head;
for (int i = 0; i < idx; i++) temp = temp->next;
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
}
size--;
return temp->data;
}
}
Node<T> *operator[](int idx){
Node<T> *temp = head;
for (int i = 0; i < idx; i++) temp = temp->next;
return temp;
}
void Print(){
Node<T> *temp = head;
for (int i = 0; i < size; i++){
cout << temp->data << " ";
temp = temp->next;
}
cout << "\n";
}
};
template<typename T>
class Queue{
private:
int idx;
LinkedList<T> queue;
public:
Queue(){
idx = -1;
}
bool isEmpty(){return (idx == -1);}
void add(T data){queue.add(data, ++idx);}
T pop(){
if (isEmpty()) cout << "queue is Empty\n";
else{
idx--;
return queue.pop(0);
}
}
};
int main(){
Queue<int> q;
cout << "q.isEmpty(): " << q.isEmpty() << "\n";
cout << "q.pop(): " << q.pop() << "\n";
q.add(123);
q.add(234);
q.add(345);
q.add(456);
q.add(567);
q.add(678);
cout << "q.isEmpty(): " << q.isEmpty() << "\n";
cout << "q.pop(): " << q.pop() << "\n";
}