Unit - 2
Stacks and Queues
Q1) What is ADT?
A1)
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc.
Stack Example
A real-world stack allows operations at one end only. For example, we can place or remove a card or plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation.
Q2) Explain the basic operations in stack?
A2)
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
Push() − Pushing (storing) an element on the stack.
Pop() − Removing (accessing) an element from the stack.
Stack Push Operation
If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically.
Algorithm for PUSH Operation
A simple algorithm for Push operation can be derived as follows −
Begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
End procedure
Implementation of this algorithm in C, is very easy.
See the following code −
Example
Void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value. But in linked-list implementation, pop() actually removes data element and deallocates memory space.
A Pop operation may involve the following steps −
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Stack Pop Operation
Algorithm for Pop Operation
A simple algorithm for Pop operation can be derived as follows −
Begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
End procedure
Implementation of this algorithm in C, is as follows −
Example
Int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
Q3) Explain the applications of stack?
A3)
There are many real-life examples of a stack. Consider the simple example of plates stacked over one another in a canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO/FILO order.
Time Complexities of operations on stack:
Push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations.
Applications of stack:
- Balancing of symbols
- Infix to Postfix /Prefix conversion
- Redo-undo features at many places like editors, photoshop.
- Forward and backward feature in web browsers
- Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
- Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver
- In Graph Algorithms like Topological Sorting and Strongly Connected Components
Stack data structure is used for evaluating the given expression. For example, consider the following expression
5 * ( 6 + 2 ) - 12 / 4
Since parenthesis has the highest precedence among the arithmetic operators, ( 6 +2 ) = 8 will be evaluated first. Now, the expression becomes
5 * 8 - 12 / 4
* and / have equal precedence and their associativity is from left-to-right. So, start evaluating the expression from left-to-right.
5 * 8 = 40 and 12 / 4 = 3
Now, the expression becomes
40 - 3
And the value returned after the subtraction operation is 37.
Q4) What is ADT queue?
A4)
A Queue is a linear list in which data is inserted at one end called as rear and deleted from other end called as front. Queue removes elements in the same order in which they were inserted i.e. element inserted first is removed first. Hence they are called as First-in-First out( FIFO) data structure.
Imagine a queue of people waiting for a bus. The person in the front of queue will get a first chance to board a bus. The person at the rear will be last one to board a bus. Same case is of checkout line in a grocery store or a cafeteria, list of jobs to be processed by computer or a list of calls on mobile phone.Fig.1 shows queue of alphabets. Alphabets are added at rear and removed from front end.
A Front | B | C | D | E | F Rear |
Fig. Queue of alphabets
We will see queue with respect to an example. Imagine queue of alphabets with size of three. Initially queue is empty.
Front |
|
Rear |
Now let us add an element in a queue. So queue becomes
Front |
| A Rear |
Add one more element ’B’ in a queue. Since element can only be inserted at rear, A progresses through queue and B is inserted at rear. Now queue becomes
Front | A | B Rear |
Adding one more element ‘C’ in queue
A Front | B | C Rear |
Now queue is full. If we try to insert one more element in queue then queue overflow occurs.
Now remove elements from queue. Element in queue is always removed from front end. Currently ‘A’ is at front end and hence will be removed first.
B Front | C |
Rear |
Removing ‘B’ and ‘C’ we get
Front |
|
Rear |
Now queue is empty. If we try to remove elements from queue, queue underflow occurs.
Q5) What are the operations in queue?
A5)
Operations on Queue:
- Bool enqueue(TYPE in): Insert elements at rear of queue.
- Bool dequeue(TYPE & out): Remove elements from front of queue.
- Bool Front(TYPE& out): Determines element at the front of queue.
- Bool Rear(TYPE& in): Determines element at the rear of queue.
- Int Count():Determines total number of elements present in queue.
- Bool isEmpty():Determines if queue is empty.
- Bool isFull():Determines if queue is full.
Q6) Explain simple queue?
A6)
Template <class TYPE>
Struct Node//Node declaration
{
TYPE value;//data in a node
};
Template <class TYPE> //class template for queue
Class Queue
{
Private:
Node<TYPE> * P;//pointer to node
Int count;// number of elements present in queue
Int max; // maximum queue size
Int front; //index of element at front
Int rear // index of element at rear
Public:
Queue(int size=50);
~Queue();
Bool enqueue(TYPE in);
Bool dequeue(TYPE& out);
Bool QFront(TYPE& out);
Bool QRear(TYPE& out);
Int QCount();
Bool isEmpty();
Bool isFull();
};
Q7) Explain circular queue?
A7)
Template <class TYPE>
Struct Node//Node declaration
{
TYPE value;//data in a node
};
Template <class TYPE> //class template for queue
Class Queue
{
Private:
Node<TYPE> * P;//pointer to node
Int count;// number of elements present in queue
Int max; // maximum queue size
Int front; //index of element at front
Int rear // index of element at rear
Public:
Queue(int size=50);
~Queue();
Bool enqueue(TYPE in);
Bool dequeue(TYPE& out);
Bool QFront(TYPE& out);
Bool QRear(TYPE& out);
Int QCount();
Bool isEmpty();
Bool isFull();
};
We will see array implementation for
- Linear Queue
- Circular Queue
We assume queue of size 7. Intially Queue is empty. So
Count=0
Front=rear=-1;
Max=7
Q8) Explain Priority queue?
A8)
A priority queue is an ADT where every element has a "priority" associated with it. This priority determines the order in which they exit the queue. The elements with highest priority are removed before elements with low priority. If two elements have the same priority, they are removed according to their order in the queue.
Consider the scenario of jobs sent to a printer. These jobs are usually placed in a queue, so job that is submitted first will be printed first. But every time this is not feasible as some of the jobs are more important though they are submitted later. So these important jobs should have precedence over other jobs which are submitted earlier. Such kind of application requires priority queue.
The common operations on priority queue are
- Insert: Inserts element in priority queue. It is similar to enqueue operation of Queue.
- Delete: finds and removes the element from priority queue. It is similar to dequeue operation of Queue. The element removed is of highest priority.
Q9) Explain the implementation of priority queue?
A9)
All the functions are same as that of normal queue except dequeue as here element is deleted according to priority. We will look at dequeue function.
Let us assume array Q[] of size n.
TYPE dequeue ()
{
int max = 0;
// finding the index of the element with the highest priority
for (int i=0; i<n-1; i++)
{
if (Q[i] > Q[max])
{
max = i;
}
}
TYPE maxnum = Q[max];
size--;
Q[max] = Queue[n];
return maxnum;
delete maxnum;
}
Q10) Explain the operations on each type of queue?
A10)
Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the memory. Here we shall try to understand the basic operations associated with queues −
Enqueue() − add (store) an item to the queue.
Dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient. These are −
Peek() − Gets the element at the front of the queue without removing it.
Isfull() − Checks if the queue is full.
Isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in the queue we take help of rear pointer.
Let's first learn about supportive functions of a queue −
Peek()
This function helps to see the data at the front of the queue. The algorithm of peek() function is as follows −
Algorithm
Begin procedure peek
return queue[front]
End procedure
Implementation of peek() function in C programming language −
Example
Int peek() {
return queue[front];
}
Isfull()
As we are using single dimension array to implement queue, we just check for the rear pointer to reach at MAXSIZE to determine that the queue is full. In case we maintain the queue in a circular linked-list, the algorithm will differ. Algorithm of isfull() function −
Algorithm
Begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
End procedure
Implementation of isfull() function in C programming language −
Example
Bool isfull() {
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
Isempty()
Algorithm of isempty() function −
Algorithm
Begin procedure isempty
if front is less than MIN OR front is greater than rear
return true
else
return false
endif
End procedure
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence empty.
Here's the C programming code −
Example
Bool isempty() {
if(front < 0 || front > rear)
return true;
else
return false;
}
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
Insert Operation
Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen situations.
Algorithm for enqueue operation
Procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
End procedure
Implementation of enqueue() in C programming language −
Example
Int enqueue(int data)
if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
End procedure
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation −
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Remove Operation
Algorithm for dequeue operation
Procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
End procedure
Implementation of dequeue() in C programming language −
Example
Int dequeue() {
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
return data;
}