-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.cpp
85 lines (67 loc) · 1.58 KB
/
queue.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
#include <iostream>
using namespace std;
struct Node{
int val;
Node *next;
};
struct Queue{
Node *head, *tail;
int size;
};
Node* createNode(int value){
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->val = value;
newNode->next = nullptr;
return newNode;
}
Queue* createQueue(){
Queue *newQueue = (Queue*) malloc(sizeof(Queue));
newQueue->head = newQueue->tail = nullptr;
newQueue->size = 0;
return newQueue;
}
int isEmpty(Queue *myQueue){
if(myQueue->tail == nullptr) return 1;
else return 0;
return -1;
}
void enqueue(int value, Queue *myQueue){
Node *node = createNode(value);
if(isEmpty(myQueue)){
myQueue->head = myQueue->tail = node;
}
else{
myQueue->tail->next = node;
myQueue->tail = node;
}
myQueue->size++;
}
void dequeue(Queue *myQueue){
if(isEmpty(myQueue)){
cout << "Nothing to dequeue" << endl;
return;
}
Node *temp = myQueue->head;
myQueue->head = myQueue->head->next;
if(myQueue->head == nullptr) myQueue->tail == nullptr;
free(temp);
if(myQueue->size == 1){
myQueue->tail = myQueue->head;
}
myQueue->size--;
}
int main(){
Queue *myQ = createQueue();
enqueue(3, myQ);
dequeue(myQ);
enqueue(7, myQ);
enqueue(5, myQ);
dequeue(myQ);
enqueue(10, myQ);
cout << "Head: " << myQ->head->val << endl;
cout << "Tail: " << myQ->tail->val << endl;
dequeue(myQ);
cout << "Head: " << myQ->head->val << endl;
cout << "Tail: " << myQ->tail->val << endl;
return 0;
}