-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingLinkedList.cpp
More file actions
135 lines (120 loc) · 2.3 KB
/
QueueUsingLinkedList.cpp
File metadata and controls
135 lines (120 loc) · 2.3 KB
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
#include <iostream>
#include <stdio.h>
#define QUEUE_UNDERFLOW 1;
using namespace std;
struct node
{
int item;
node *next;
};
class Queue
{
private:
node *front; // point to start node
node *rear; // point to last node
public:
Queue();
Queue(Queue &);
Queue &operator=(Queue &);
void insertElement(int);
int getRear();
int getFront();
void deleteFront();
int countElement();
~Queue();
};
Queue::Queue() // initially both node pointers containing null;
{
front = rear = NULL;
}
Queue::Queue(Queue &q)
{
front = rear = NULL;
node *r = q.front;
while (r != NULL)
{
insertElement(r->item);
r = r->next;
}
}
Queue &Queue::operator=(Queue &q)
{
while (front)
deleteFront();
node *r = q.front;
while (r != NULL)
{
insertElement(r->item);
r = r->next;
}
return *this;
}
void Queue::insertElement(int data)
{
node *n = new node; // prepare node
n->item = data;
n->next = NULL;
if (front == NULL) // if linked List is empty
{
front = n;
rear = n;
}
else // if linked list has one element or more
{
rear->next = n;
rear = n;
}
}
int Queue::getRear()
{
if (rear == NULL)
throw QUEUE_UNDERFLOW;
return rear->item;
}
int Queue::getFront()
{
if (front == NULL)
throw QUEUE_UNDERFLOW;
return front->item;
}
void Queue::deleteFront()
{
if (front == NULL)
{
throw QUEUE_UNDERFLOW;
}
else if (front->next == NULL) // or we can say that front == rear i.e list has only one element
{
delete front;
front = rear = NULL;
}
else
{
node *r = front;
front = front->next;
delete r;
}
}
int Queue::countElement()
{
if(front==NULL)
return 0;
else if(front->next == NULL)
return 1;
else
{
node *r = front;
int count=1;
while(r->next == NULL)
{
count++;
r = r->next;
}
return count;
}
}
Queue::~Queue()
{
while (front)
deleteFront();
}