Week4 Queue Circular
Week4 Queue Circular
Pointer in
Stack
Pointers
in Queue
Where to Best Use What?
Stacks Queues
For storing data It is useful to store
elements, when the data elements
you need recently when you want to
added object to be treat or process
treated / processed element which is
first added first
E.g.: Recent
operations
performed in word
Operations of Stacks VS
Queues
For an empty stack set top to • For an empty queue set rear
-1 and front to -1
isempty() : Return true if • isempty() : Return true if
stack is empty, return false stack is empty, return false
otherwise
otherwise
• isfull(): returns full if the
Is full(): returns full if the queue is full
stack is full • Peek(): Returns the
top() : Return top element of element at front
stack • dequeue() : Remove an
pop() : Remove the top element from the front of
element from the stack the queue
push(x) : Add element x at • enqueue(x) : Add element
x at the rear of the queue
the top of the stack
CS2143 Data Structures
Implementation – Queue
public class Queue
{private:
int array [5];
int front, rear, count;
public:
Queue() …
bool isEmpty() …
void display() …
void dequeue() …
int peek()…
bool isFull() …
void enqueue (int value) …
}
Queue()
{
rear
front = rear = -1;
count = 0; 2
0 1
}
CS2143 Data Structures
front
Implementation – isEmpty()
bool isEmpty()
{
if (front== -1)
return true;
else
return false;
}
bool isFull()
{
if (front ==4)
return true;
else
return false;
}
CS2143 Data Structures
Implementation –peek()
int peek()
{
return array[front];
}
bool isEmpty()
{
if(front == -1 )
{
return true;
}
else
{
return false;
}
}
Implementation – IsFull()
bool isFull()
{
if(front == 0 && rear == SIZE - 1)
{ return true; }
return false;
}
Implementation – Enqueue()
void enqueue(int x)
{
if(isFull())
cout << "Queue is full";
else
{
if(front == -1)
front = 0; rear = (rear + 1) % SIZE; // going round and round concept
array[rear] = x; // inserting the element
cout << endl << "Inserted " << x << endl;
}
}
Implementation – Dequeue()
void dequeue()
{
if(isEmpty())
cout << "Queue is empty" << endl;
else
{
if(front == rear) // only one element in queue, reset queue after removal
{
front = -1;
rear = -1;
}
else
front = (front+1) % SIZE;
}
}
Applications of Queues