-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueType.cpp
138 lines (117 loc) · 2.5 KB
/
QueType.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
#include <cstddef> // For NULL
#include <new> // For bad_alloc
#include "QueType.h"
struct NodeType
{
ItemType info;
NodeType* next;
};
QueType::QueType() // Class constructor.
// Post: front and rear are set to NULL.
{
front = NULL;
rear = NULL;
}
void QueType::MakeEmpty()
// Post: Queue is empty; all elements have been deallocated.
{
NodeType* tempPtr;
while (front != NULL)
{
tempPtr = front;
front = front->next;
delete tempPtr;
}
rear = NULL;
}
// Class destructor.
QueType::~QueType()
{
MakeEmpty();
}
bool QueType::IsFull() const
// Returns true if there is no room for another ItemType
// on the free store; false otherwise.
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch(std::bad_alloc)
{
return true;
}
}
bool QueType::IsEmpty() const
// Returns true if there are no elements on the queue; false otherwise.
{
return (front == NULL);
}
void QueType::Enqueue(ItemType newItem)
// Adds newItem to the rear of the queue.
// Pre: Queue has been initialized.
// Post: If (queue is not full) newItem is at the rear of the queue;
// otherwise a FullQueue exception is thrown.
{
if (IsFull())
throw FullQueue();
else
{
NodeType* newNode;
newNode = new NodeType;
newNode->info = newItem;
newNode->next = NULL;
if (rear == NULL)
front = newNode;
else
rear->next = newNode;
rear = newNode;
}
}
void QueType::Dequeue(ItemType& item)
// Removes front item from the queue and returns it in item.
// Pre: Queue has been initialized and is not empty.
// Post: If (queue is not empty) the front of the queue has been
// removed and a copy returned in item;
// othersiwe a EmptyQueue exception has been thrown.
{
if (IsEmpty())
throw EmptyQueue();
else
{
NodeType* tempPtr;
tempPtr = front;
item = front->info;
front = front->next;
if (front == NULL)
rear = NULL;
delete tempPtr;
}
}
QueType::QueType
(const QueType& anotherQue)
{
NodeType* ptr1;
NodeType* ptr2;
if (anotherQue.front == NULL)
front = NULL;
else
{
front = new NodeType;
front->info = anotherQue.front->info;
ptr1 = anotherQue.front->next;
ptr2 = front;
while (ptr1 != NULL)
{
ptr2->next = new NodeType;
ptr2 = ptr2->next;
ptr2->info = ptr1->info;
ptr1 = ptr1->next;
}
ptr2->next = NULL;
rear = ptr2;
}
}