L7b - Queue ADT
L7b - Queue ADT
Queue ADT
Major Operations
Enqueue: Items are added to the back of the queue
Dequeue: Items are removed from the front of the
queue
Get Front: Take a look at the first item
[ CS1020E AY1516S2 Lecture 7b ]
3
Queue: Illustration
private:
// Implementation dependant
// See subsequent implementation slides
};
0 1 2 3 4 5 6 7 8 9
front A B C D E F G
back
Visualized as a
circular array 9 0 front
8 1
A
B
C 2
// Advancing front and back index
7
front = (front+1) % maxsize;
G D back = (back+1) % maxsize;
back F E 3
6
4
[ CS1020E AY1516S2 Lecture 7b ]
10
Queue ADT (Array): C++ Specification
const int MAX_QUEUE = 50; // here is the main problem of array
// our queue cannot be that large
template<typename T>
class Queue {
public:
Queue();
bool isEmpty() const;
int size() const;
private:
T _items[MAX_QUEUE];
int _front, _back, _count;
};
QueueA.h
Queue Queue
Front Back
Queue Queue
Front Back
private:
struct QueueNode { Just like a ListNode
T item; structure, yes we can use
QueueNode *next; inheritance but ListLL.h in
}; Lecture6 is an SLL
int _size;
QueueNode *_lastNode;
};
QueueLL.h
[ CS1020E AY1516S2 Lecture 7b ]
18
Insertion: Non-Empty Queue
Step 1:
newNode = new QueueNode;
newNode->next = lastNode->next;
newNode->item = 3;
This value is just
Step 2: an example only
lastNode->next = newNode;
Step 3:
lastNode = newNode;
[ CS1020E AY1516S2 Lecture 7b ]
19
Insertion: Empty Queue
Step (a):
newNode = new QueueNode;
newNode->item = 3;
Set up the “loop”
Step (b):
newNode->next = newNode;
lastNode = newNode;
Step 1:
QueueNode* firstNode = lastNode->next;
Step 2:
lastNode->next = firstNode->next;
delete firstNode;
firstNode firstNode
Step 1:
QueueNode* firstNode = lastNode->next;
Step 2:
lastNode = null;
delete firstNode;
Many solutions
But for the sake of discussion, let’s use the two newly
learned ADTs
Highlight the difference of LIFO and FIFO property
Main Idea
Use stack to reverse the input
Use queue to preserve the input
The two sequence should be the same for palindrome
[ CS1020E AY1516S2 Lecture 7b ]
27
Palindrome: Implementation
#include <queue>
#include <stack>
using namespace std;
Uses Uses
Implements Implements