-
Notifications
You must be signed in to change notification settings - Fork 0
/
lqueue.h
100 lines (84 loc) · 2.21 KB
/
lqueue.h
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
// header file lqueue.h
// linked queue
#ifndef LinkedQueue_
#define LinkedQueue_
//#include "node.h"
#include "xcept.h"
template<class T>
class LinkedQueue {
// FIFO objects
public:
LinkedQueue() {front = rear = 0;} // constructor
~LinkedQueue(); // destructor
int IsEmpty() const
{return ((front) ? 0 : 1);} //false : true);}
int IsFull() const;
T First() const; // return first element
T Last() const; // return last element
LinkedQueue<T>& Add(const T& x);
LinkedQueue<T>& Delete(T& x);
private:
Node<T> *front; // pointer to first node
Node<T> *rear; // pointer to last node
};
template<class T>
LinkedQueue<T>::~LinkedQueue()
{// Queue destructor. Delete all nodes.
Node<T> *next;
while (front) {
next = front->link;
delete front;
front = next;
}
}
template<class T>
int LinkedQueue<T>::IsFull() const
{// Is the queue full?
Node<T> *p;
try {p = new Node<T>;
delete p;
return 0;} //false;}
catch (NoMem) {return 1;} //true;}
}
template<class T>
T LinkedQueue<T>::First() const
{// Return first element of queue. Throw
// OutOfBounds exception if the queue is empty.
if (IsEmpty()) throw OutOfBounds();
return front->data;
}
template<class T>
T LinkedQueue<T>::Last() const
{// Return last element of queue. Throw
// OutOfBounds exception if the queue is empty.
if (IsEmpty()) throw OutOfBounds();
return rear->data;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Add(const T& x)
{// Add x to rear of queue. Do not catch
// possible NoMem exception thrown by new.
// create node for new element
Node<T> *p = new Node<T>;
p->data = x;
p->link = 0;
// add new node to rear of queue
if (front) rear->link = p; // queue not empty
else front = p; // queue empty
rear = p;
return *this;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Delete(T& x)
{// Delete first element and put it in x. Throw
// OutOfBounds exception if the queue is empty.
if (IsEmpty()) throw OutOfBounds();
// save element in first node
x = front->data;
// delete first node
Node<T> *p = front;
front = front->link;
delete p;
return *this;
}
#endif