0% found this document useful (0 votes)
101 views

Unit 3 Stacks and Queue

The document discusses stacks and queues. It begins by introducing stacks and describing their LIFO nature and common operations like push and pop. It discusses stack implementation using arrays and linked lists. Applications of stacks include reversing lists and converting infix to postfix notation. The document also introduces queues and their FIFO nature. It provides examples of queue representation and applications like linear queues.

Uploaded by

Durvankur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Unit 3 Stacks and Queue

The document discusses stacks and queues. It begins by introducing stacks and describing their LIFO nature and common operations like push and pop. It discusses stack implementation using arrays and linked lists. Applications of stacks include reversing lists and converting infix to postfix notation. The document also introduces queues and their FIFO nature. It provides examples of queue representation and applications like linear queues.

Uploaded by

Durvankur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Stacks and Queue

Unit 3
Outline
 Introduction of stacks
Stack Operations –PUSH, POP
Stack Operations conditions- Stack Full/Stack Overflow, Stack Empty/Stack Underflow
Stack representation in Memory using Array and Link List.
Stack as ADT
Applications of stacks
Reversing a list
Polish Notations

 Conversions of infix to postfix expression, Evaluation of postfix expression, evaluation of Prefix


expression, recursion, tower of Hanoi,.

 Queue
Queue as an ADT.
Representation of Queue.
Types of Queue.
Applications of Linear Queue
Introduction of stacks

 Stack is non primitive linear data structure.


 Works on the principal of Last In First Out (LIFO).
 The last item pushed onto the stack is always the first to be removed from the
stack.
 Example : stack of books
 Implementation of most of the system programs is based on stack data
structure,
 Restricted that elements are added or deleted at only one end of the list called
as TOP of stack.
Stack Operations

 PUSH: To insert an element into stack.


 POP: To delete an element from stack.
Stack operations
Stack Operations conditions-

 Stack Full/Stack Overflow: this is the situation when the stack is full and no
more elements can be PUSHED onto stack. This is required for the PUSH
operation because we cannot push in full stack.
 Stack Empty/Stack Underflow: Checks whether the stack is empty. This
operation returns TRUE if the stack is empty and false otherwise. This is
required for the POP operation because we cannot pop from an empty stack.
Representation of stack
 Static representation of stack using Array.
 It is useful for fixed sized stack
 Easy and convenient.
 In this representation every new element is inserted at TOP.
 Stack can be represented using a one dimensional array. Allocate a block of
memory required to store the full capacity of stack, and the items of stack are
stored in a sequential manner from the first location of memory block.
Representation of stack
 Dynamic representation of stack uses linked list.
 Singly Linked list is used for this representation.
 In linked list the first element inserted into the stack is pointed out by the
second element, the second element by the third and so on. The (n-1)th element
is pointed out by nth element.
 The only possible element that can be removed or popped is top element and
node can be inserted by becoming the new head node.
 The linked list implementation of a stack requires the following:
 Structure declaration containing some n fields, and
 Pointer to the previous node or the next node.
Difference

Stack representation using array Stack representation using LL

Less space is used for each data element as no pointer is used. More space is used for each node.

The memory space is wasted if we store less elements than the maximum Memory space is not wasted as space is allocated only when user wants.
size of array.
Insertion and deletion involve more data movement. Insertion and deletion involve less data movement.

It does not provide flexibility because the size of stack is fixed. It provides flexibility as the size can grow as per requirement.

It is called static implementation of stack. It is called dynamic implementation of stack.


Stack as an ADT
 Stack js are ordered LIFO.
 The stack ADT is defined by the writing its structure and operations.
 One can write following functions and their functionality:
 CREATE: This operation is used to create an empty stack and value of
TOP is -1.
 PUSH: it is the process of adding a new element to the TOP of stack.
 POP: It is the process of deleting an element from the TOP of stack.
 isEmpty(): This operation checks whether the stack is empty.
 isFull(): This operation checks whether the stack is full.
 Size(): It returns the number of elements in the stack.
 TOP(): It returns the first element on the TOP.
 Display: This displays the items in the stack.
PUSH and POP operations Algo
 Algo for PUSH operation
 PUSH( STACK, TOP, MAX, ITEM)
 TOP=MAX-1the print OVERFLOW and Return.
 Set TOP= Top-1.(Increase TOP by 1)
 Set STACK[TOP]= ITEM. (Insert ITEM at new TOP position).
 Return.

 Algo for POP operation


 If TOP=-1 the print UNDERFLOW and Return.
 Set ITEM= STACK[TOP]. (Assign TOP element to ITEM)
 Set TOP= TOP-1. (Decrease the TOP by 1)
 Return.
Applications of stack
 Polish Notations.
 Conversion of Infix to postfix expression.
 Conversion of infix to prefix expression.
 Evaluation of postfix expression.
 Evaluation of prefix expression.
 Recursion.
 Reversing a string.
 Backtracking.
Stacks are widely used in operating systems by compiler and by application.
Stacks are also used in procedure call, subroutine calls, interrupt handling, well
formed parentheses(matching parentheses in an expression), decimal to binary
conversion.
Polish Notations

 An algebraic expression is a legal combination of operators and operands.


 Operand is the quantity on which a mathematical operation is performed.
Operand may be a variable like x, y, z or a constant like 5, 4, 6 etc.
 Operator is a symbol which signifies a mathematical or logical operation
between the operands. Examples of familiar operators include +, -, *, /, ^etc.
 An algebraic expression can be represented using three different notations.
They are infix, postfix and pre fix notations
Polish notations

 Infix: It is the form of an arithmetic expression in which we fix (place) the


arithmetic operator in between the two operands.
Example: (A + B) * (C - D)
 Prefix: It is the form of an arithmetic notation in which we fix (place) the
arithmetic operator before(pre) its two operands.
Example: * + A B – C D
 Postfix: It is the form of an arithmetic expression in which we fix (place) the
arithmetic operator after (post) its two operands. Example: A B + C D -
*
Operator Precedence

 We consider five binary operations: +, -, *, / and $ or or ^ (exponentiation). For


these binary operations, the following in the order of precedence (highest to
lowest)
Conversion of Infix to Postfix Expression
Procedure to convert from infix expression to postfix expression is as follows:
Scan the infix expression from left to right.
Initialize an empty stack.
Repeat steps till all the characters are scanned.
If the scanned symbol is left parenthesis, push it onto the stack.
If the scanned symbol is an operand, then place directly in the postfix expression(output).
If the symbol scanned is a right parenthesis, then go on popping all the items from the
stack and place them in the postfix expression till we get the matching left parenthesis.
If the scanned symbol is an operator, then go on removing all the operators from the stack
and place them in the postfix expression, if and only if the precedence of the operator
which is on the top of the stack is greater than (or greater than or equal) to the precedence
of the scanned operator and push the scanned operator onto the stack otherwise, push the
scanned operator onto the stack.
If the stack is not empty add top stack to output string and Pop the stack.. Repeat till the
stack is empty.
Convert the infix expression A+(B*C-(D/E^F)*G)*H
into equivalent postfix expression
Conversion of Infix to Prefix Expression
Procedure to convert from infix expression to postfix expression is as follows:
Scan the infix expression from right to left.
Intialize an empty stack.
Repeat steps till all the characters are scanned.
If the scanned symbol is right parenthesis, push it onto the stack.
If the scanned symbol is an operand, then place directly in the postfix expression(output).
If the symbol scanned is a left parenthesis, then go on popping all the items from the stack and
place them in the postfix expression till we get the matching left parenthesis.
If the scanned symbol is an operator, then go on removing all the operators from the stack and
place them in the postfix expression, if and only if the precedence of the operator which is on the
top of the stack is greater than (or greater than or equal) to the precedence of the scanned operator
and push the scanned operator onto the stack otherwise, push the scanned operator onto the stack.
If the stack is not empty add top stack to output string and Pop the stack.. Repeat till the stack is
empty.
Read the Postfix string in reverse to get Prefix string.
Convert the infix expression (A+B*C-D)/(E*F) into equivalent prefix expression
Input Character Stack Postfix string Operation

) )

F ) F

* )* F

E )* FE

( EMPTY FE*

/ / FE*

) /) FE*

D /) FE*D

- /)- FE*D

C /)- FE*DC

* /)-* FE*DC

B /)-* FE*DCB

+ /)-+ FE*DCB*

A /)-+ FE*DCB*A

( / FE*DCB*A+-

FE*DCB*A+-/
Evaluation of postfix expression
 Algorithm
Scan the arithmetic operation from left to right and repeat the steps until ‘\o’ is
encountered.
If an operand is encountered put it on the stack.
If an operator is encountered then
Remove the top 2 elements of stack. (top element and next to top element)
Evaluate the operation on operant 1 and operand 2
Place the result back on to the stack
Set the value to the top of stack to get final outcome.
Exit.
Evaluation of postfix expression
evaluate the expression 234+*6-
Evaluation of postfix expression
Reversing a String
Recursion
 When a function definition includes a call to itself, it is referred to as recursive
function.
 For storing all values in a function a stack is maintained(current values of
parameters, local variables and the return address) .
 When a function calls itself space is set aside in memory to execute. For second
function again the space is set aside and so on.
 These memory areas for each function call are arranged in the stack. When
the execution of call is complete the place at the top is removed.
 It should satisfy the properties
 The arguments must have certain base values means it should have statement for
termination.
 Each time the function calls itself it should get closer to the base value.
Tower of Hanoi
 The tower of Hanoi is puzzle invented by French mathematician.
 This is mathematical puzzle which has 3 towers and more than one disk.
 There are disk are of different size stacked upon each other in ascending order.
The number of disk can increase but the number of tower remain same.
 Tower of Hanoi puzzle with n disk can be solved in minimum 2^n-1 steps.
 Rules:
 You have to move the disk from on tower to other without disturbing the sequences
of arrangements.
 Only one disk can be moved at one time.
 Only ‘TOP’ disk can be removed.
 No large disk can sit on small disk.
Tower of Hanoi puzzle example for 3 number of disk.
This presentation shows that a puzzle with 3 disks has taken
2^3-1=7 steps.
Queue
 Queue is non primitive data structure. Queue is a ADT
 Queue is an ordered and homogenous collection of elements where elements
are deleted at front end and inserter at rear end.
 It is called FIFO..
Types of Queue
 Linear Queue: Linear DS where insertion is at one end and deletion at other end..
It is FIFO. In linear queue elements are arranged in sequential mode such that
front position is always be less than or equal to the rear position.

 Circular Queue: all the nodes are treated as circular. Last node is connected back to
first node. Circular queue is also called as Ring Buffer.

 Dequeue (double ended queue): in double ended queue insert and delete operation
can be at both ends that is front and rear.

 Priority Queue: It contains items which have some preset priority. While deleting
an element in the queue the data item with the highest
priority is removed first.
Queue as an ADT
 The entities are added to rear terminal position called as enqueue and removal of entities
from the front terminal position called as dequeue. This is FIFO(first in first out) structure.
 The queue operations are given below:
 enqueue() add a new item to rear.
 dequeue() remove the front item.
 Queue() create a new queue.
 Front() returns front element from queue.
 Rear() returns rear element from queue.
 isEmpty() to check whether the queue is empty.
 size() to know the number of items in the queue.
 C implementation for a queue: array is used to store the elements and variables front and rear
hold the position of first and last elements of the queue.
 struct queue
{
int item[10], front, rear;
} q;
Representation of Queue

 Static implementation using array:


 A one dimensional array is used to represent a queue
 The variable front and rear keep track of front and rear ends of the queue.
 The size of the array is decided before execution at compile time.
 Once the array is declared, its size cannot be altered during run time of the
program.
 The queue cannot hold more than n elements and must check the condition
whether the queue is full before insertion and queue is empty before deletion.
 In C queue using array is represented by
 Int Q[20];
 int front = -1;
 int rear= -1;
Representation of Queue

 Advantages and disadvantages of static implementation:


 Using array is easy and convenient.
 Memory wastage is possible if less number of elements are stored
than the maximum size.
 Only fixed number of elements are stored in queue.
Representation of Queue

 Dynamic implementation using Linked list:


 It may be required to increase the size of the queue during execution. So queue could be
implemented dynamically using linked list.
 Unlimited number of elements could be added to queue using linked list.
 enqueue() operation is used to enter new element. It will create a new node by allocating
a memory to it and then insert it into linked list by checking the front. If front is NULL
the first element is inserted into queue and rear and front will point to that element. if
front is not NULL this new node will be assigned rear. So the new node is the new rear.
 dequeue() removes the front element from the linked list and assigns front pointer to next
node. It checks if the queue is empty before deleting as element couldn’t be deleted from
empty queue.
 traverse() this will traverse all the elements in the queue if it is not empty. When the last
elements next field is NULL it will stop traversing.
Representation of Queue

 Advantages and disadvantages of dynamic representation of queue.


 There is no wastage of memory.
 Size of queue is not fixed.
 Any numbers of elements could be inserted into queue.
 Insertion and deletion are easy to perform.
 Needs extra space for pointer fields.
Difference between stack and queue

Stack Queue

Stack is LIFO(last In first out) Queue is FIFO(first in first out)

Insertion and deletion take place at only one end called as TOP Insertion takes place at REAR and deletion take place at FRONT.

Stack has pointer variable TOP for operations Queue has two pointer variables front and rear for operations.

Operations on stack are PUSH and POP Operations on queue are ENQUEUE and DEQUEUE.

It is used for procedure calls or interrupt handling It is used for time sharing system.

Eg: Eg:
Stack of dishes etc People waiting at bus stop.
Linear Queue
 Queue is the ordered list in which all insertions take place at one end called
rear and deletions take place at the other end called front.
 Basic features of queue are:
 This is FIFO.
 Queue is also an ordered list of elements of similar data types.
 Two pointers FRONT and REAR are used for insertion and deletion.
 When queue is empty Front and Rear are -1.
 When Front =0 and Rear=max-1 queue is full.
Operations on Queue.
Algorithm for enqueue() and dequeue() in
linear queue.

 ENQUEUE() Algorithm:
 Queue[max] be the array for queue. Front and Rear are initialize to -1. Item be the
element to be inserted.
If rear= max-1 then
print queue is overflow
Else
if front=-1 set front to 0
set rear=rear+1
set Queue[rear]= Item. // item inserted at rear position.
Algorithm for enqueue() and dequeue() in
linear queue.

 DEQUEUE Algorithm:
 Queue[max] be the array for queue. Front and Rear are initialize to -1.
If front=-1
Print queue is underflow
Else
Set value=queue[front] //delete the element which is at the front of queue
Set front=front+1
if front>rear then set both front and rear to -1
Need of Circular Queue.
 Insertion is not possible even if the queue is empty in linear queue.
Circular Queue
 In this queue all nodes are circular so that the first node follows last node. It is
also known as Ring Buffer.
Operations on circular queue
Algorithm for enqueue() and dequeue() in circular
queue.

 ENQUEUE() Algorithm:
 Let Queue[0-max-1] is an array having max capacity. Both front and rear are
initialize to -1.
If ((front==0) and rear==max-1) or (rear==front-1)
print overflow.
if (front==-1)
front=rear=0
else
rear=(rear+1)%max
Queue[rear]= element
Algorithm for enqueue() and dequeue() in
circular queue.

 DEQUEUE() Algorithm:
 Let Queue[0-max-1] is an array having max capacity. Both front and rear are
initialize to -1.
If(front==-1)
print underflow
Element= Queue[front]
If(front==rear)
front=rear=-1
Else
front=(front+1)%max
Priority Queue

 Priority queue is the special kind of queue data structure in which insertion
and deletion operations are performed according to some special rule rather
than just FIFO rule.
 In case of priority queue, a priority number is associated with each element.
 The elements are inserted and deleted according to this priority number.
 The following two rules are applied to process the elements in the priority
queue:
 1. The elements with higher priority are processed before the elements with lower
priority.
 2. In case of elements with same priority, elements are processed according to the
First In First Out (FIFO) rule.
 Eg: queue in an hospital.
Priority Queue

 Priority queues can be represented into the memory in following ways:


 Priority Queue using linked list
 Priority Queue using multiple queues
 Priority Queue using heap structure
Operations on Priority Queue

 In linked list representation of priority queue, each node of the linked list is
divided into three parts as shown below:

 Info part holds the element of the queue.


 Priority part holds the priority number of the element.
 Next part holds the address of next node of linked list info Priority Next
 In linked list representation of priority queue, insertion of an element takes
place according to the priority number of the element where as the deletion
takes place from front end of linked list.
Operations on Priority Queue
Operations on Priority Queue
Applications of Queue
 Linear Queue:
 Printing using computer
 Reservation system
 Computer networks
 Categorization of data
 Circular Queue
 Adding Large Integers
 Memory management
 Computer controlled traffic signals
 Priority Queue:
 To find kth largest element
 Sorting
 Job scheduling

You might also like