[Data Structure] Queue

Queue

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
#include <iostream>
using namespace std;
template <class T>
class Node {
private:
T data;
Node* next;
public:
Node(T d) : data(d) {
next = NULL;
}
T getData() {
return data;
}
Node* getNext() {
return next;
}
void setNext(Node* n) {
next = n;
return;
}
};

template <class T>
class Queue {
public:
Node<T> *Head;
Node<T> *Tail;
Node<T> *cur;
int size;
public:
Queue(T d) {
size = 1;
Head = new Node(d);
Tail = Head;
}
Queue() {
size = 0;
Head = NULL;
Tail = NULL;
}
void pop() {
cur = Head->getNext();
free(Head);
Head = cur;
size--;
}
void push(T d) {
if (size==0) {
Head = new Node<T>(d);
Tail = Head;
}
else {
cur = Tail;
Tail = new Node<T>(d);
cur->setNext(Tail);
}
size++;
}
T front() {
return Head->getData();
}
};
int main(int argc, char** argv) {
Queue<int> q;
for (int i = 0; i < 13; i++) {
q.push(i);
}
for (int i = 0; i < 13; i++) {
cout << q.front() << endl;
q.pop();
}
return 0;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/21/DataStructure/queue/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.