0% found this document useful (0 votes)
23 views98 pages

Unit-4 - Stacks and Queues

The document provides a comprehensive overview of Stack and Queue data structures, detailing their basic principles, operations, and implementations using arrays and linked lists. It explains the Last-In-First-Out (LIFO) principle for stacks and the First-In-First-Out (FIFO) principle for queues, along with their applications in various programming scenarios. Additionally, it covers algorithms for stack operations such as push and pop, and discusses infix to postfix conversion using stacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views98 pages

Unit-4 - Stacks and Queues

The document provides a comprehensive overview of Stack and Queue data structures, detailing their basic principles, operations, and implementations using arrays and linked lists. It explains the Last-In-First-Out (LIFO) principle for stacks and the First-In-First-Out (FIFO) principle for queues, along with their applications in various programming scenarios. Additionally, it covers algorithms for stack operations such as push and pop, and discusses infix to postfix conversion using stacks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

Stack & Queue

Mahendra Pratap Yadav


Computer Science & Engineering
Indian Institute of Information Technology Pune
Outline

*Stack *Queue
* Basic principles * Basic principles
* Operation of stack * Operation of queue
* Stack using Array * Queue using Array
* Stack using Linked List * Queue using Linked List
* Applications of stack * Applications of queue

Data Structures and Algorithms @Mahendra


Stack

Data Structures and Algorithms @Mahendra


Basic Idea
•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.

Data Structures and Algorithms @Mahendra


What is a Stack?
A stack is an Abstract Data Type (ADT),
commonly used in most programming
languages.
A Stack is a linear data structure that follows
the LIFO (Last-In-First-Out) principle.
It contains only one pointer top
pointer pointing to the topmost element of the
stack.
Whenever an element is added in the stack, it
is added on the top of the stack, and the
element can be deleted only from the stack.
Stack Representation

•Can be implemented by means of Array, Structure, Pointers and


Linked List.
•Stack can either be a fixed size or dynamic.
Data Structures and Algorithms @Mahendra
push

pop

create
STACK
isempty

isfull

Data Structures and Algorithms @Mahendra


STACK: Last-In-First-Out (LIFO)
•void push (stack *s, int element);
/* Insert an element in the stack */
•int pop (stack *s);
/* Remove and return the top element */
•void create (stack *s);
/* Create a new stack */
•int isempty (stack *s);
/* Check if stack is empty */
•int isfull (stack *s);
/* Check if stack is full */
Assumption: stack contains integer elements!
Data Structures and Algorithms @Mahendra
Stack using Array

Data Structures and Algorithms @Mahendra


Push using Stack

PUSH

top
top

Data Structures and Algorithms @Mahendra


Pop using Stack

POP

top
top

Data Structures and Algorithms @Mahendra


Stack using Linked List

Data Structures and Algorithms @Mahendra


Push using Linked List

PUSH OPERATION

top

Data Structures and Algorithms @Mahendra


Pop using Linked List

POP OPERATION

top

Data Structures and Algorithms @Mahendra


Basic Idea
•In the array implementation, we would:
•Declare an array of fixed size (which determines the maximum
size of the stack).

•Keep a variable which always points to the “top” of the stack.


•Contains the array index of the “top” element.

•In the linked list implementation, we would:


•Maintain the stack as a linked list.
•A pointer variable top points to the start of the list.
•The first element of the linked list is considered as the stack
Data Structures and Algorithms @Mahendra
top.
Declaration

#define MAXSIZE 100 struct lifo


{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST

Data Structures and Algorithms @Mahendra


Stack Creation

void create (stack *s) void create (stack **top)


{ {
s->top = -1; *top = NULL;
/* s->top points to /* top points to NULL,
last element indicating empty
pushed in; stack */
initially -1 */ }
}

ARRAY LINKED LIST

Data Structures and Algorithms @Mahendra


Push Operation
The process of putting a new data element onto stack is
known as a Push Operation. Push operation involves a
series of steps −
❖ Step 1 − Checks if the stack is full.

❖ Step 2 − If the stack is full, produces an error and


exit.

❖ Step 3− If the stack is not full, increments top to


point next empty space.

❖ Step 4 − Adds data element to the stack location,


where top is pointing.

❖ Step 5 − Returns success.


18
Push Operation

19
Pushing an element into stack
Algorithm to push an element into stack− Array

20
Pushing an element into stack
Algorithm to push an element into stack− Linked List

21
Pushing an element into stack

void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc
printf (“\n Stack (sizeof(stack));
overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}

ARRAY LINKED LIST


Data Structures and Algorithms @Mahendra
POP Operation
Accessing the content while removing it from the stack,
is known as a Pop Operation. 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.


23
Pop Operation

24
Popping an element from stack

Algorithm to pop an element− Array

25
Popping an element from stack

Algorithm to pop an element− Linked List

26
Popping an element from stack

int pop (stack **top)


int pop (stack *s) {
int t;
{ stack *p;
if (s->top == -1)
if (*top == NULL)
{ {
printf (“\n Stack printf (“\n Stack is empty”);
underflow”); exit(-1);
exit(-1); }
else
}
{
else t = (*top)->value;
{ p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
return t;
} }
}

ARRAY LINKED LIST


Data Structures and Algorithms @Mahendra
Checking for stack empty

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

Data Structures and Algorithms @Mahendra


Checking for Stack Full

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

Data Structures and Algorithms @Mahendra


Application of Stack Data Structure

Stack is used for expression evaluation


Stack is used for parenthesis matching while
working with expressions.
Stack is used in expression conversion. For
example, infix to postfix or prefix to postfix
Stack is used in memory management
It is used in java virtual machine
It is used for the Backtracking problem-solving
method
Application of Stack Data Structure

It is used in string parsing or string reversal.


Stack is used to matching the HTML tags in web
development
Stack is also used in function call for recursive
functions.
Applications of Stacks
•Direct applications:
•Page-visited history in a Web browser
•Undo sequence in a text editor
•Chain of method calls in the Java Virtual Machine
•Validate XML

•Indirect applications:
•Auxiliary data structure for algorithms
•Component of other data structures
Data Structures and Algorithms @Mahendra
Infix and Postfix Notations
•Infix: operators placed between operands:
A+B*C
•Postfix: operands appear before their operators:-
ABC*+
•There are no precedence rules to learn in postfix notation, and
parentheses are never needed

Data Structures and Algorithms @Mahendra


Partial Table of Operator Precedence and
Associativity

Operator Associativity

() ++ (postfix) -- (postfix) left to right

+(unary) -(unary) ++(prefix) --(prefix) right to left

* / % left to right

+ - left to right

= += -= right to left
Operators on the top line have the highest precedence.
Precedence decreases line-by-line going down the table.
All operators on the same line have equal precedence.
34
Infix to Postfix

Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+

A + B * C 🡪 (A + (B * C)) 🡪 (A + (B C *) ) 🡪 A B C * +

A + B * C + D 🡪 ((A + (B * C)) + D ) 🡪 ((A + (B C*) )+ D) 🡪


((A B C *+) + D) 🡪 A B C * + D +
Data Structures and Algorithms @Mahendra
Evaluation of postfix expression -

36
Evaluation of postfix expression -

37
Evaluation of postfix expression -

38
Infix to postfix conversion
•Use a stack for processing operators (push and pop operations).
•Scan the sequence of operators and operands from left to right and
perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains operator of a lower
precedence and push the present operator.

39
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until
you see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the
stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association.
If the association is left to right, pop and print the top of the stack and then push the
incoming operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack,
pop the stack and print the top operator. Then test the incoming operator against the
new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)
40
Infix to Postfix Conversion
Requires operator precedence information

Operands:
Add to postfix expression.

Close parenthesis:
pop stack symbols until an open parenthesis appears.

Operators:
Pop all stack symbols until a symbol of lower precedence appears.
Then push the operator.

End of input:
Pop all remaining stack symbols and add to the expression.

41
Infix to Postfix Conversion

42
Infix to Postfix Conversion

43
Example - Conversion Infix to Postfix

44
Example - Conversion Infix to Postfix

45
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E
2 * * A
3 ( *( A
becomes
4 B *( AB
ABCD*+*E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
is also called as 9 ) * ABCD*+
Reverse Polish 10 + + ABCD*+*
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
Data Structures and Algorithms @Mahendra
Tower of Hanoi

Data Structures and Algorithms @Mahendra


Tower of Hanoi

Data Structures and Algorithms @Mahendra


Queue

Data Structures and Algorithms @Mahendra


Basic Idea
•Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to
insert data (enqueue) and the other is used to remove data (dequeue).

Data Structures and Algorithms @Mahendra


Basic Idea
•Non-primitive linear data structure.
•A new element is added at one end called rear end and the existing
elements are deleted from the other end called front end.
•This mechanism is called First-In-First-Out (FIFO).
•e.g. People standing in Queue for Movie Ticket

Data Structures and Algorithms @Mahendra


Fig: Model of a Queue

*
Queue Representation

•As in stacks, a queue can also be implemented using Arrays,


Linked-lists, Pointers and Structures.

Data Structures and Algorithms @Mahendra


enqueue

dequeue

create
QUEUE
isempty

size

Data Structures and Algorithms @Mahendra


QUEUE: First-In-First-Out (LIFO)
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */

Assumption: queue contains integer elements!

@Mahendra Data Structures and Algorithms


Basic Operations
❖ Queue operations may involve initializing or
defining the queue, utilizing it and then completing
erasing it from memory.

❖ enqueue − add store an item to the queue.


❖ dequeue − remove access an item from the
queue.

❖ Few more functions are required to make above


mentioned queue operation efficient. These are
❖ peek − get the element at front of the queue
without removing it
❖ isfull − checks if queue is full.
❖ isempty − checks if queue is empty.
Queue Specification
*Definitions:
*MAX_ITEMS: Max number of items that might be on
the queue
*ItemType: Data type of the items on the queue

• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Enqueue (ItemType newItem)
– Dequeue (ItemType& item)
Peek ()
a. This function helps to see the data at the front of the queue.
Algorithm of peek function − .

begin procedure peek

return queue[front]

end procedure
a. Implementation of peek function in C programming
language 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 queue is full.
In case we maintain queue in a circular linkedlist, the
algorithm will differ. Algorithm of isfull function −

begin procedure isfull


if rear equals to MAXSIZE
return true
else
return false
endif
end procedure
isfull()
a. Implementation of isfull function in C programming
language
bool isfull()
{
if(rear == MAXSIZE
- 1)
return true;
else
return false;
}
isempty()
a. Algorithm of isempty function−
begin procedure isempty
if front is less than MIN OR front is greater
than rear
return true
else
return false
endif
end procedure
If value of front is less than MIN or 0, it tells that queue
is not yet initialized, hence empty
isempty()
Implementation of peek function in C
programming language
bool isempty()
{
if(front < 0 || front > rear)
return true;
else
return false;
}
Enqueue (ItemType newItem)

*As queue maintains two data pointers, front and rear, its
operations are comparatively more difficult to implement
than stack.

*Function: Adds new Item to the rear of the queue.


*Preconditions: Queue has been initialized and is not full.
*Postconditions: new Item is at rear of queue.
Enqueue Operation
*The following steps should be taken to enqueue insert data into
a queue −
❖ Step 1 − Check if queue is full.

❖ Step 2 − − If queue is full, produce overflow error and


exit.

❖ Step 3− If queue is not full, increment rear pointer to


point next empty space.

❖ Step 4 − Add data element to the queue location,


where rear is pointing.

❖ Step 5 − Returns success.


Enqueue Operation
Algorithm for enqueue operation
Enqueue Operation
*Implementation of enqueue in C programming language −
int enqueue(int data)
if(isfull())
return 0;

rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
Dequeue (ItemType& item)
*Function: Removes front item from queue and returns it in item.
*Preconditions: Queue has been initialized and is not empty.
*Postconditions: Front element has been removed from queue and
item is a copy of removed element.
Dequeue Operation
*Accessing data from 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 queue is empty.


❖ Step 2 − If queue is empty, produce underflow error and
exit.
❖ Step 3− − If queue is not empty, access data where front
is pointing.
❖ Step 4 − − Increment front pointer to point next available
data element.
❖ Step 5 − Returns success.
Dequeue Operation
Algorithm for dequeue operation
Queue using Linked List

Data Structures and Algorithms @Mahendra


Basic Idea
•Basic idea:
•Create a linked list to which items would be added to one end and
deleted from the other end.
•Two pointers will be maintained:
•One pointing to the beginning of the list (point from where
elements will be deleted).
•Another pointing to the end of the list (point where new Rear
elements will be inserted).

Front DELETION INSERTION


Data Structures and Algorithms @Mahendra
Queue: Linked List Structure

ENQUEUE

front rear

Data Structures and Algorithms @Mahendra


Queue: Linked List Structure

DEQUEUE

front rear

Data Structures and Algorithms @Mahendra


Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};

struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;

void enqueue (QUEUE *q,int element)


{
struct qnode *q1;
q1=(struct qnode *)malloc(sizeof(struct qnode));
q1->val= element;
q1->next=q->qfront;
q->qfront=q1;
}

Data Structures and Algorithms @Mahendra


Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q)
prev->next=NULL;
{
free(q1);
queue *q1;
return (val);
q1=q;
}
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}

Data Structures and Algorithms @Mahendra


Problem With Array Implementation
•The size of the queue depends on the number and order of enqueue
and dequeue.
•It may be situation where memory is available but enqueue is not
possible. ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N

front
front rearrear

Use of circular array indexing


Data Structures and Algorithms @Mahendra
Circular Queues
7 18 14 36 45 21 99 72
0 1 2 3 4 5 6 7 8
9

• We will explain the concept of circular queues using an example.


• In this queue, front = 2 and rear = 9.
• Now, if you want to insert a new element, it cannot be done
because the space is available only at the left of the queue.
• If rear = MAX – 1, then OVERFLOW condition exists.
• This is the major drawback of an array queue. Even if space is
available, no insertions can be done once rear is equal to MAX – 1.
• This leads to wastage of space. In order to overcome this problem,
we use circular queues.
• In a circular queue, the first index comes right after the last index.
• A circular queue is full, only when front=0 and rear = Max – 1.
Inserting an Element in a Circular Queue
• For insertion we check for three conditions which are as follows:
▪ If front=0 and rear= MAX – 1, then the circular queue is full.
90 49 7 18 14 36 45 21 99 72

front=0 1 2 3 4 5 6 7 8 rear = 9

▪ If rear != MAX – 1, then the rear will be incremented and value will
be inserted
90 49 7 18 14 36 45 21 99

front=0 1 2 3 4 5 6 7 rear= 8 9

• If front!=0 and rear=MAX -1, then it means that the queue is


not full. So, set rear = 0 and insert the new element.
49 7 18 14 36 45 21 99 72

front=1 2 3 4 5 6 7 8 rear= 9
Inserting an Element in a Circular Queue

• rear = front -1 overflow

9 10 7 18 14 36 45 21 99 72

rear=1 front=2 3 4 5 6 7 8
9
Algorithm to Insert an Element in a Circular Queue

Step 1: IF FRONT=0 and REAR=MAX–1, or REAR = FRONT – 1 then


Write “OVERFLOW”
Goto Step 4
[END OF IF]

Step 2: IF FRONT = -1 and REAR = -1, then;


SET FRONT = REAR = 0
ELSE IF REAR = MAX – 1 and FRONT != 0
SET REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: Exit
Deleting an Element from a Circular Queue
• To delete an element again we will check for three conditions:
▪ If front = -1, then it means there are no elements in the queue. So
an underflow condition will be reported.

0 1 2 3 4 5 6 7 8
9

▪ If the queue is not empty and after returning the value on front, if
front = rear, then it means now the queue has become empty and
so front and rear are set to -1.
Delete this element and set
81 rear = front = -1
0 1 2 3 4 5 6 7 8
front=rear= 9

▪ If the queue is not empty and after returning the value on front, if
front = MAX -1, then front is set to 0.
72 63 9 18 27 39 81
0 1 2 3 4 rear= 5 6 7 8
front= 9
Algorithm to Delete an Element from a Circular Queue
Step 1: IF FRONT = -1, then
Write “Underflow”
Goto Step 4
[END OF IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END OF IF]
[END OF IF]
Step 4: EXIT
4. Queue by Linked List
• Using a singly linked list to hold queue elements,
Using FRONT pointer pointing the start element,
Using REAR pointer pointing to the last element.

• Insertions is done at the rear end using REAR pointer


Deletions is done at the front end using FRONT pointer

• If FRONT = REAR = NULL, then the queue is empty.

1 7 3 4 2 6 5 X

FRONT REAR
Inserting an Element in a Linked Queue
Algorithm to insert an element in a linked queue

Step 1: Allocate memory for the new node and


name the pointer as PTR
Step 2: SET PTR->DATA = VAL
Step 3: IF FRONT = NULL, then
SET FRONT = REAR = PTR
SET FRONT->NEXT = REAR->NEXT = NULL
ELSE
SET REAR->NEXT = PTR
SET REAR = PTR
SET REAR->NEXT = NULL
[END OF IF]
Step 4: END

Time complexity: O(1)


Deleting an Element from a Linked Queue

Algorithm to delete an element from a


linked queue

Step 1: IF FRONT = NULL, then


Write “Underflow”
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: FRONT = FRONT->NEXT
Step 4: FREE PTR
Step 5: END

Time complexity: O(1)


5. Deques
• A deque (double-ended queue) is a list in which
elements can be inserted or deleted at either end.
• Also known as a head-tail linked list because elements
can be added to or removed from the front (head) or
back (tail).
• A deque can be implemented either using a circular array
or a circular doubly linked list.
• In a deque, two pointers are maintained, LEFT and RIGHT
which point to either end of the deque.
Deque variants
• There are two variants of deques:
– Input restricted deque: In this dequeue insertions can be
done only at one of the ends while deletions can be done
from both the ends.
– Output restricted deque: In this dequeue deletions can be
done only at one of the ends while insertions can be done
on both the ends.

29 37 45 54 63
0 1 2 LEFT = 3 4 5 6 RIGHT = 7 8
9

63 27 18
42
RIGHT = 0 1 2 3 4 5 6 LEFT = 7 8
9
6. Priority Queues
• A priority queue is a queue in which each element is assigned a
priority.
• The priority of elements is used to determine the order in which
these elements will be processed.
• The general rule of processing elements of a priority queue can be
given as:
o An element with higher priority is processed before an element
with lower priority
o Two elements with same priority are processed on a first come
first served (FCFS) basis
• Priority queues are widely used in operating systems to execute the
highest priority process first.
• In computer’s memory priority queues can be represented using
arrays or linked lists.
Linked List Representation of Priority Queues

• When a priority queue is implemented using a linked list, then


every node of the list contains three parts: (1) the information or
data part, (ii) the priority number of the element, (iii) and address
of the next element.
• If we are using a sorted linked list, then element having higher
priority will precede the element with lower priority.

A 1 B 2 C 3 D 3 E 4 X

Priority queue after insertion of a new node


(F, 4)
A 1 B 2 C 3 D 3 E 4 F 4 X
Array Representation of Priority Queues
• When arrays are used to implement a priority queue, then a
separate queue for each priority number is maintained.
• Each of these queues will be implemented using circular arrays
or circular queues. Every individual queue will have its own
FRONT and REAR pointers.
• We can use a two-dimensional array for this purpose where each
queue will be allocated same amount of space.
• Given the front and rear values of each queue, a two
dimensional matrix can be formed.
7. Applications of Queues
1. Queues are widely used as waiting lists for a single
shared resource like printer, disk, CPU.
2. Queues are used to transfer data asynchronously
e.g., pipes, file IO, sockets.
3. Queues are used as buffers on MP3 players and
portable CD players, iPod playlist.
4. Used to handle interrupts in the operating system
5. The queue is used in the round-robin scheduling
algorithm
7. Applications of Queues
5. Queues are used in Playlist for jukebox to add songs to the
end, play from the front of the list.
6. Queues are used in OS for handling interrupts.
7. When programming a real-time system that can be
interrupted, for example, by a mouse click, it is necessary
to process the interrupts immediately before proceeding
with the current job.
8. If the interrupts have to be handled in the order of arrival,
then a FIFO queue is the appropriate data structure
Difference between Stack & Queue
Stack Queue

The stack is based on LIFO(Last In First Out) The queue is based on FIFO(First In First Out)
principle principle.

Insertion Operation is called Push Operation Insertion Operation is called Enqueue Operation

Deletion Operation is called Pop Operation Deletion Operation is called Dequeue Operation

Push and Pop Operation takes place from one Enqueue and Dequeue Operation takes place
end of the stack from a different end of the queue

The most accessible element is called Top and The insertion end is called Rear End and the
the least accessible is called the Bottom of the deletion end is called the Front End.
stack
Simple Implementation Complex implementation in comparison to stack

Only one pointer is used for performing Two pointers are used to perform operations
operations
Difference between Stack & Queue
Stack Queue

Empty condition is checked using Empty condition is checked using


Top==-1 Front==-1||Front==Rear+1
.
Full condition is checked using Full condition is checked using
Top==Max-1 Rear==Max-1
There are no variants available for stack There are three types of variants i.e circular
queue, double-ended queue and priority queue

Can be considered as a vertical collection Can be considered as a horizontal collection


visual visual

Used to solve the recursive type problems Used to solve the problem having sequential
processing
Applications of Queues
•Direct applications:-
• Waiting lists
• Access to shared resources (e.g., printer)
• Multiprogramming
•Indirect applications:-
• Auxiliary data structure for algorithms
• Component of other data structures

Data Structures and Algorithms @Mahendra


Any question?

Data Structures and Algorithms @Mahendra

You might also like