DSA - Stacks and Queues
DSA - Stacks and Queues
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
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 three primary operations −
push − pushing (storing) an element on the stack.
pop − removing (deleting) an element from the stack.
Parsing
Recursive Function
Function Call
Expression Evaluation Expression Representation
Expression Conversion Sr Expressi Meaning
Infix to Postfix # on
1 5 4
Position 1 2 3 4 5 6 7 8
TOP 3
TOP = 0 indicates that the stack is empty and TOP = N indicates that the stack is full
Since all the action happens at the top of the stack, a single linked list is a fine way to
represent the stack wherein the header/start always points to the top of the stack.
CC BB AA X
Represents Top
Pushing is inserting an element at the front of the list
Popping is removing an element from the front of the list
CC BB AA X
After Push
DD CC BB AA X
School of Computer Engineering
Stack - Linked List Representation
11
DD CC BB AA X
After Pop
CC BB AA X
Stack Node Representation
struct node
{
int info;
struct node *next; N represents NULL
}*top;
void push()
{
int data; Top
scanf(“%d”, &data); Top
if (top == NULL)
{
top =(struct node *)malloc(*sizeof(struct node));
C
top->next = NULL; B
top->info = data; C B
} A X PUSH
else
{ X represents NULL A X
void pop()
{
struct node *tempTop = top;
Top
if (tempTop == NULL) Top
{
printf("\n Error "); C
return;
B
} B POP
else
tempTop = tempTop ->next; A X
A X
free(top);
top = tempTop;
2 î 3 + 5 * 2 î 2 – 12 / 6
= 8 + 5 * 4 – 12 / 6 = 8 + 20 – 2 = 26
An arithmetic expression can be written in three different but equivalent
notations, i.e., without changing the essence or output of an expression. These
notations are −
Infix Notation Postfix Notation
Prefix Notation
Example
It is not a very efficient way to design an algorithm or program to parse infix notations.
Instead, these infix notations are first converted into either postfix or prefix notations
and then computed. To parse any arithmetic expression, we need to take care of operator
precedence and associativity also.
Precedence :- When an operand is in between two different operators, which operator
will take the operand first, is decided by the precedence of an operator over others. For
example − a + b *c a + (b * c)
Associativity :- It describes the rule where operators with the same precedence appear
in an expression. For example, in expression a + b − c, both + and – have the same
precedence, then which part of the expression will be evaluated first, is determined by
associativity of those operators. Here, both + and − are left associative, so the expression
will be evaluated as (a + b) − c.
Postfix:
Computer usually evaluates an arithmetic expression written in infix notation in
two steps:
1st Step - Converts the infix notation to Postfix notation
2nd Step - Evaluates the Postfix expression.
In each step, stack is the main tool used to accomplish the given task.
Prefix:
Has seen wide application in Lisp (programming language) s-expressions
Data Compression with Prefix Encoding
Standard scientific prefixes are used to denote powers of 10 e.g. kilo = 1e3
mega = 1e6 tera = 1e12 exa = 1e18
giga = 1e9 peta = 1e15
1. Start
2. Validate the Postfix expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is after the operands [Binary operators are considered only]
3. Add a right parenthesis ‘)” at the end of P. [This act as delimiter]
4. Scan P from left to right and repeat steps 5 and 6 for each element of P until the
delimiter “)” is encountered
5. If an operand is encountered, put it on STACK
6. If an operator is encountered, then
(a) Remove the two top elements of STACK, where A is the top element and B is the
next-to-top element
(b) Evaluate B A
(c ) Place the result of step (b) on STACK
7. Set value of the postfix expression equal to the top element of STACK
P = 5, 6, 2, + , *, 12, 4, /, - [Postfix]
Note – Commas are used to separate the elements of P so that 5,6,2 is not interpreted as 562.
Q = 12 / (7-3) + 2 * (1+5) = 15
1. Start
2. Validate the Prefix Expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is before the operands [Binary operators are considered only]
3. Scan P from right to left and repeat steps 4 and 5 for each element of P until it ends.
4. If an operand is encountered, put it on STACK
5. If an operator is encountered, then
(a) Remove the two top elements of STACK, where A is the top element and B is the
next-to-top element
(b) Evaluate A B
(c ) Place the result of step (b) on STACK
6. Set value of the prefix expression equal to the top element of STACK
7. Stop
P = -, *, +, 4, 3, 2, 5 [Prefix]
Note – Commas are used to separate the elements of P
- * + 4 3 2 5
(7) (6) (5) (4) (3) (2) (1)
Symbol STACK
scanned
(1) 5 5
(2) 2 5 2
(3) 3 5 2 3
(4) 4 5 2 3 4
(5) + 5 2 7
(6) * 5 14
(7) - 9
Q is an arithmetic expression written in infix notation. This algorithm InfixToPostfix (Q, P) finds the equivalent
postfix notation where P is the equivalent postfix notation –
1. Start
2. Validate the Infix expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is between the operands [Binary operators are considered only]
3. Push “(“ onto STACK and “)” to the end of Q
4. Scan Q from Left to Right and Repeat Steps 5 to 8 for each element of Q until the STACK is empty
5. If an operand is encountered, add it to P
6. If a left parenthesis is encountered, push it onto STACK
7. If an operator is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator which has same precedence or higher precedence
than .
(b) Add to STACK.
8. If a right parenthesis is encountered, then
(a) Repeatedly pop from the STACK and add to P each operator until a left parenthesis is encountered.
(b) Remove the left parenthesis. [Do not add it to P]
9. Stop
Q:A+(B*C–(D/E îF)*G)*H
So first, we push “(“ onto stack, and then add “)” to the end of the Q to obtain:
A+( B * C - ( D/ E î F ) * G) * H )
1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 19 20
0 1 2 3 4 5 6 7 8
A+( B * C - ( D/ E î F ) * G) * H )
1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 19 20
0 1 2 3 4 5 6 7 8
Symbol Scanned STACK Expression P
8 ( (+(-( ABC*
9 D (+(-( ABC*D
10 / (+(-(/ ABC*D
11 E (+(-(/ ABC*DE
12 î (+(-(/î ABC*DE
13 F (+(-(/î ABC*DEF
14 ) (+(- ABC*DEFî/
15 * (+(-* ABC*DEFî/
16 G (+(-* A B C * D E F î /G
17 ) (+ ABC*DEFî/G*-
18 * (+* ABC*DEFî/G*-
19 H (+* ABC*DEFî/G*-
H
Consider the infix expression Q: ((A + B) * D) î (E-F). Translate Q into its equivalent
postfix expression P
Symbol Scanned STACK Expression P
1 ( ((
2 ( (((
3 A ((( A
4 + (((+ A
5 B (((+ AB
6 ) (( AB +
7 * ((* AB +
8 D ((* AB +D
9 ) ( AB +D*
10 î (î AB +D*
11 ( (î( AB+D*
12 E (î( AB+D*E
13 - (î(- AB+D*E F
14 F (î(- AB+D*E F
15 ) (î AB+D*E F–
Q is an arithmetic expression written in infix notation. This algorithm InfixToPrefix(Q, P) finds the
equivalent postfix notation where P is the equivalent prefix notation –
1. Start
2. Validate the Infix expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is between the operands [Binary operators are considered only]
3. Reverse the expression
4. CALL InfixToPostfix (Q, P)
5. Reverse the expression
6. Stop
Q : (A+B î C)*D+E î F
Step 1 – Infix expression is correct
Step 2 –
a) Reversing the expression produce F î E + D * ) C î B + A (
b) Reverse the bracket, so making every '(' as ')' and every ')' as '(‘
revised expression is F î E + D * ( C î B + A )
Step 3 – Postfix expression of step 2 produce F E î D C B î A + * +
Step 4 – Reversing the expression produced in step 3 becomes
+*+Aî BCDî EF
Result: + * + A î B C D î E F
deleted first, and the element that is inserted last is deleted last.
Items are inserted one end (rear end) and deleted from the other end(front end).
Operating System
queue of print jobs to send to the printer
queue of programs / processes to be run
queue of network data packets to send
Programming
modeling a line of customers or clients
storing a queue of computations to be performed in order
Real World
people on an escalator or waiting in a line
cars at a gas station (or on an assembly line)
4 8 6
Position 1 2 3 4 5 6 7 8
Keeps track of the number of items in the queue and the position of the front element
(at the front of the queue), the rear element (at the rear). The position of the front
element is stored in the front member variable. The next item is after the first one and
so on until the rear of the queue that occurs at the index stored in a member variable
called rear.
FRONT = 0 and REAR = 0 indicates that the queue is empty and REAR = N indicates that
1 2 3 4 5 6 ... FRONT
0
0 REAR
1. Start
2. IF (REAR = N) THEN
DISPLAY “OVERFLOW”
EXIT
END IF
3. IF (FRONT = 0 AND REAR = 0) THEN [Queue initially empty]
FRONT = 1
REAR = 1
ELSE
REAR = REAR + 1
END IF
4. QUEUE[REAR] = ITEM [This inserts new element]
5. Stop
1 2 3 4 5 6 ...
1 FRONT
4 8 6
3 REAR
Let’s an element leaves the queue
1 2 3 4 5 6 ...
2 FRONT
4 8 6
3 REAR
Node Representation
struct node
{
char info[50];
struct node *next;
}*front, *rear;
School of Computer Engineering
Enqueue Operation
42
Post Insertion
Post Deletion
Once the linear queue is full, even though few elements from the front are deleted & some
occupied space is relieved, it is not possible to add anymore new elements, as the rear has
already reached the queue’s rear most position.
Delete 3 elements
This situation also says that queue is full and we can not insert the new
element because, 'rear' is still at last position. In above situation, even
though we have empty positions in the queue we can not make use of them
to insert new element. This is the major problem in normal queue data
structure. To overcome this problem we use circular queue data structure.
Circular Queue is a linear data structure in which the operations are performed based on
FIFO (First In First Out) principle and the last position is connected back to the first
position to make a circle and the graphical representation of a circular queue is as
follows...
Circular Queue can be represented using − Static Array − Storing the items
contiguously (fixed size) and avoids the wastage of space in a regular queue
implementation using arrays.
Rear
Rear
Rear
Rear
OR
OR
A priority queue is a collection of elements such that each element has been assigned a
priority and such that the order in which elements are deleted and processed comes from the
following rules –
An element of higher priority is processed before any element of lower priority
Two elements with the same priority are processed according to the order in which they
Each node in the list would contain three information namely an information
field INFO, a priority number field PRN and the address field NEXT.
Systematic diagram
FRONT REAR
A1 B2 C2 D3
level of priority.
FRONT[K] and REAR[K] contains the front and rear elements of row K of queue, the
2 B C G
3 0 0
3
4 E D 4 5 1
5 4 4
School of Computer Engineering
5 F
Priority Queue – Array Representation cont…
66
1. Start
2. ?
3. Stop
Peek
1. Start
2. ?
13. Write an algorithm or c code segment for insertion, deletion, peek and traversal
of priority queue using dynamic arrays.
14. Write an algorithm or c code segment for insertion, deletion, peek and traversal
of priority queue using linked list.
15. Write an algorithm or c code segment to reverse the queue
16. Write an algorithm or c code segment to reverse the first k elements in the queue
17. The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods
and a number of disks of different sizes, which can slide onto any rod. The puzzle
starts with the disks in a neat stack in ascending order of size on one rod, the
smallest at the top, thus making a conical shape. The objective of the puzzle is to
move the entire stack to another rod, obeying the following simple rules:
• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack.
• No disk may be placed on top of a smaller disk.
Design an iterative and recursive algorithm or write a C program
18. Write an algorithm or c code segment to implement 2 queues using static array.
19. In a party of N people, only one person is known to everyone. Such a person may be
present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask
questions like “does A know B? “. Find the stranger (celebrity) in minimum number
of questions.
20. Find the largest rectangular area possible in a given histogram where the largest
rectangle can be made of a number of contiguous bars. For simplicity, assume that all
bars have same width and the width is 1 unit. For example, consider the following
histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle
possible is 12 (see the below figure, the max area rectangle is highlighted in red)
1. You are given 2 queues where each queue contains timestamp pair price. You have to
print < price 1 price 2 > for all those timestamps where abs(ts1 – ts2) <= 1 second
where ts1 and price 1 from 1st queue and ts2 and price 2 from 2nd queue.
2. Given an array, print the Next Greater Element (NGE) for every element. The Next
greater Element for an element x is the first greater element on the right side of x in
array. Elements for which no greater element exist, consider next greater element as
-1. Examples:
a) For any array, rightmost element always has next greater element as -1.
b) For an array which is sorted in decreasing order, all elements have next greater
element as -1.
c) For the input array [4, 5, 2, 25}, the next greater elements for each element are as
follows.
Element NGE
4 5
5 25
2 25
25 -1
3. Suppose there is a circle. There are n petrol pumps on that circle. You are given two
sets of data.
Calculate the first point from where a truck will be able to complete the circle (The
truck will stop at each petrol pump and it has infinite capacity). Expected time
complexity is O(n). Assume for 1 litre petrol, the truck can go 1 unit of distance.
For example, let there be 4 petrol pumps with amount of petrol and distance to next
petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where
truck can make a circular tour is 2nd petrol pump. Output should be “start = 1”
(index of 2nd petrol pump).
4. Given an array of non-negative integers. Find the largest multiple of 3 that can be
formed from array elements. For example, if the input array is {8, 1, 9}, the output
should be “9 8 1”, and if the input array is {8, 1, 7, 6, 0}, output should be “8 7 6 0”.
5. Given an array and an integer k, find the maximum for each and every contiguous
subarray of size k.
Examples:
Input :
arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, k = 3
Output :
3345556
Input :
arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 4
Output :
10 10 10 15 15 90 90
6. Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1
or 2 which has the following meaning:
0: Empty cell, 1: Cells have fresh oranges, 2: Cells have rotten oranges .
So we have to determine what is the minimum time required so that all the oranges
become rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-
1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every
orange then simply return -1.
Examples:
Input: arr[][C] = { {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
Output:
All oranges can become rotten in 2 time frames.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
What is Stack?
Stacks are data structures that allow us to insert and remove items. The operate
like a stack of papers or books on our desk - we add new things to the top of the
stack to make the stack bigger, and remove items from the top as well to make
the stack smaller. This makes stacks a LIFO (Last In First Out) data structure –
the data we have put in last is what we will get out first.
What is Queue?
A queue is a data structure where we add elements at the back and remove
elements from the front. In that way a queue is like “waiting in line”: the first
one to be added to the queue will be the first one to be removed from the queue.
This is also called a FIFO (First In First Out) data structure.
Implement Stack using Queue: We are given a stack data structure with push
and pop operations, the task is to implement a queue using instances of stack
data structure and operations on them.
Solution: [Link]
Implement Queue using Stack: We are given a queue data structure with
enqueue and deque operations, the task is to implement a stack using instances
of queue data structure and operations on them.
Solution: [Link]