Data Structure Unit III - Stack and Queue - SPJ
Data Structure Unit III - Stack and Queue - SPJ
QUEUE
Classification of Data Structures
Unit -III
■ Stack: Concept, Basic Stack operations, Array
representation of stack, Stack as ADT, Stack
Applications: Reversing data, Arithmetic expressions
conversion and evaluation.
https://www.youtube.com/watch?v=1S
Wr7q121gc&t=180s
Features of Stack
1.Stack is an ordered list of similar data type.
2.Stack is a LIFO(Last in First out) structure or we can
say FILO(First in Last out).
3.push() function is used to insert new elements into the Stack
and pop() function is used to remove an element from the
stack. Both insertion and removal are allowed at only one end
of Stack called Top.
4.Stack is said to be in Overflow state when it is completely
full and is said to be in Underflow state if it is completely
empty.
Basic operations of Stack
• Push: Adds an item in the stack. If the stack is full, then it is said to be an
Overflow condition.
• Pop: Removes an item from the stack. The items are popped in the reversed
order in which they are pushed. If the stack is empty, then it is said to be an
Underflow condition.
• Peek or Top: Returns top element of stack.
• isEmpty: Returns true if stack is empty, else false.
Push and Pop
■ Primary operations: Push and Pop
■ Push
– Add an element to the top of the stack
■ Pop
– Remove the element at the top of the stack
top
B
top top
A A A
top
7
Applications of stack
•To reverse a word - Put all the letters in a stack and pop them out. Because
of the LIFO order of stack, you will get the letters in reverse order.
•In compilers - Compilers use the stack to calculate the value of expressions
like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix or postfix
form.
•In browsers - The back button in a browser saves all the URLs you have
visited previously in a stack. Each time you visit a new page, it is added on
top of the stack. When you press the back button, the current URL is
removed from the stack and the previous URL is accessed.
• https://www.youtube.com/watch?v=d_XvFOkQz5k&list=PLhb7SOmGNU
c5AZurO-im4t_RDr-ymjz0d
Unit -III
■ Stack: Concept, Basic Stack operations, Array
representation of stack, Stack as ADT,
■ Stack Applications: Reversing data, Arithmetic
expressions conversion and evaluation.
Implementation:
• Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
• Step 2 - Declare all the functions used in stack implementation.
• Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
• Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
• Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the
stack.
Stack Operations using Array
push(stack, 10);
push(stack, 20);
push(stack, 30);
• In Stack ADT Implementation instead of data being stored in each node, the
pointer to data is stored.
• The program allocates memory for the data and address is passed to the stack
ADT.
■
Stack ADT
■ (((A+((B*C)/D))-(E*F))-G)
• Polish Postfix form:
■ A B C * D / + E F * - G -
• Polish Prefix form:= A+ /*BCD= --+A\*BDC*EFG
■ – Try it out ….
Conversion Infix to Postfix and Prefix
■ (A + (B * C))
■ Infix to Postfix= ABC*+
• Advantages:
–No concept of operator priority.
•Simplifies the expression evaluation rule.
–No need of any parenthesis.
•Hence no ambiguity in the order of evaluation.
–Evaluation can be carried out using a single scan over
the expression string.
•Using stack.
Evaluation of a Polish Expression
■ a*b+c:
■ Manually:+*abc
Conversion of Infix Expression to Prefix Expression :
Unit -III
■ Stack: Concept, Basic Stack operations, Array
representation of stack, Stack as ADT, Stack
Applications: Reversing data, Arithmetic expressions
conversion and evaluation.
■ Queue: Concept, Queue operations, Array
representation of queue, Queue as ADT, Circular
queue, Priority Queue, Applications of queue:
Categorizing data, Simulation of queue.
Queue
■ The following diagram given below tries to explain queue representation as data
structure
■ 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.
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.
■
Enqueue 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.
Dequeue Operation
int dequeue() {
if(isempty()) return 0;
int data =
queue[front]; front =
front + 1; return data;
}
Applications of Queue Data Structure
void deQueue()
{ if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{ printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1; } }
void display()
{ if(rear == -1)
printf("\nQueue is Empty!!!");
else{ int i; printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]); } }
Unit -III
■ Stack: Concept, Basic Stack operations, Array
representation of stack, Stack as ADT, Stack
Applications: Reversing data, Arithmetic expressions
conversion and evaluation.
■ Queue: Concept, Queue operations, Array
representation of queue, Queue as ADT, Circular
queue, Priority Queue, Applications of queue:
Categorizing data, Simulation of queue.
Limitation of Queue
■ As you can see in the image below, after a bit of enqueuing and dequeuing, the size of
the queue has been reduced.
The indexes 0 and 1 can only be used after the queue is reset when all the elements have been dequeued.
After REAR reaches the last index, if we can store extra elements in the empty spaces (0 and 1), we can make
use of the empty spaces. This is implemented by a modified queue called the circular queue.
Types of Queue
■ Simple Queue
■ Circular Queue
■ Priority Queue
■ Deque (Double Ended Queue)
Simple Queue
■ In a simple queue, insertion takes place at the rear and removal occurs at the front. It
strictly follows FIFO rule.
Circular Queue
■ In a circular queue, the last element points to the first element making a circular link.
The main advantage of a circular queue over a simple queue is better memory utilization. If the
last position is full and the first position is empty then, an element can be inserted in the first
position. This action is not possible in a simple queue.
How Circular Queue Works
■ Circular Queue works by the process of circular increment i.e. when we try to
increment the pointer and we reach the end of the queue, we start from the beginning
of the queue.
■ The circular increment is performed by modulo division with the queue size
■ if REAR + 1 == 5 (overflow!),
■ REAR = (REAR + 1)%5 = 0 (start of queue)
Circular Queue Operations
■ The circular queue work as follows:
• two pointers FRONT and REAR
• FRONT track the first element of the queue
• REAR track the last elements of the queue
• initially, set value of FRONT and REAR to -1
■ 1. Enqueue Operation
• check if the queue is full
• for the first element, set value of FRONT to 0
• circularly increase the REAR index by 1 (i.e. if the rear reaches the end, next it would
be at the start of the queue)
• add the new element in the position pointed to by REAR
Circular Queue Operations
2. Dequeue Operation
•check if the queue is empty
•return the value pointed by FRONT
•circularly increase the FRONT index by 1
•for the last element, reset the values of FRONT and REAR to -1
However, the check for full queue has a new additional case:
•Case 1: FRONT = 0 && REAR == SIZE - 1
•Case 2: FRONT = REAR + 1
The second case happens when REAR starts from 0 due to circular increment and when its value is just 1
less than FRONT, the queue is full.
Applications of Circular Queue
• CPU scheduling
• Memory management
• Traffic Management
Priority Queue
■ A priority queue is a special type of queue in which each element is associated with a
priority and is served according to its priority. If elements with the same priority occur,
they are served according to their order in the queue.
Priority Queue
■ Generally, the value of the element itself is considered for assigning the
priority.
■ For example, The element with the highest value is considered as the
highest priority element. However, in other cases, we can assume the
element with the lowest value as the highest priority element. In other
cases, we can set priorities according to our needs.
Priority Queue
Priority Queue
■ Queues are used in categorization. Queues categorize data into different groups
without losing the original ordering of data.
■ Example:-Library sections
■ In this, we have to perform different addition or removal operations by
maintaining their basic orders
■ This is an example of multiple Queue operations
■ Multiple queue operation can be implemented using single array.
Categorizing data using Queue
■ Multiple queue operation can be implemented using single array.
■ When queue is implemented using array, the size of array should be known in
advance.
■ Frequent overflow conditions will be encountered if queue is allocated a less
space
■ To overcome this problem, evey time modification in code to allocate more
space for the array is needed
■ If large space is allocated to queue, it may result into wastage of memory.
■ f(1)
So a better
f(1)solution
f(2) is f(2)
to have
f(3) multiple
f(3) queues
f(4) or
f(4)tof(5)
have more
f(5)than one queue
in the same array of sufficient size.
■ The programming application that uses queue is a simulation , Where real life
activity is modelled by objects
■ Example:-Airport simulation
■ How queues may be applied in real life applications by simulating an airport traffic
control program.
Simulation of queue
Problem Specification:
Write a program to simulate airport traffic control for a small but busy airport assuming
the following specifications.
q There is only one runway for both landing and take off.
q In each unit time, only one plane can land or take off but not both.
q Planes arrive and take off at random time, so that at any given unit, the runway may
q After running for some period, the program should print statistics such as: number of
planes processed, landed, and took off, refused; average landing and take-off waiting
times, and average run-way idle time.
Simulation of queue
Algorithm
Create two queues, landing and takeoff
Initialize statistics counters to zero
Loop for time unit from 1 to some fixed number
Loop from 1 to some random number of landing planes
If landing queue is not full, add plane to the queue else
refuse landing and increment number of refused.
Loop from 1 to some random number of taking off planes
If takeoff queue is not full, add plane to the queue else
refuse landing and increment number of refused.
If landing queue is not empty process next landing plane and
increment count of planes landed
Else if takeoff queue is not empty, process next plane and
increment count of take off planes
Else increment count of run-way idle time.
Print the statistics
Thank You!!
Important points
■ Infix A+B
■ Postfix AB+
■ Prefix +AB
Important points
AB+C*DE-FG++$ $=Exponent