0% found this document useful (0 votes)
68 views15 pages

Stack Adt: CS8391 Data Structures Department of CSE&IT

1) Stacks and queues are linear data structures. Stacks follow the LIFO principle while queues follow the FIFO principle. 2) The basic stack operations are push, pop, and peek. Arrays and linked lists can represent stacks. Elements are inserted and removed from one end called the top. 3) The basic queue operations are enqueue and dequeue. Elements are inserted at the rear and removed from the front. Queues can also be implemented using arrays or linked lists.

Uploaded by

Aruna Raj
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)
68 views15 pages

Stack Adt: CS8391 Data Structures Department of CSE&IT

1) Stacks and queues are linear data structures. Stacks follow the LIFO principle while queues follow the FIFO principle. 2) The basic stack operations are push, pop, and peek. Arrays and linked lists can represent stacks. Elements are inserted and removed from one end called the top. 3) The basic queue operations are enqueue and dequeue. Elements are inserted at the rear and removed from the front. Queues can also be implemented using arrays or linked lists.

Uploaded by

Aruna Raj
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/ 15

CS8391 Data Structures Department of CSE&IT

UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES

Stack ADT – Operations – Applications – Evaluating arithmetic expressions-


Conversion of Infix to postfix expression – Queue ADT – Operations – Circular
Queue – Priority Queue – deQueue –applications of queues.

STACK ADT
A stack is a linear data structure which uses the same principle, i.e., the elements in a stack are
added and removed only from one end, which is called the TOP, Hence, a stack is called a LIFO
(Last-In-First-Out) data structure, as the element that was inserted last is the first one to be
taken out.

OPERATIONS
A stack supports three basic operations:
 Push
 Pop
 Peek

ARRAY REPRESENTATION OF STACKS


In the computer’s memory, stacks can be represented as a linear array.Every stack has a variable
called TOP associated with it, which is used to store the address of the topmost element of the
stack. It is this position where the element will be added to or deleted from. There is another
variable called MAX, which is used to store the maximum number of elements that the stack
can hold.
If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then the stack is
full.

Example:

Push Operation
The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack. However, before inserting the value, we must first check if
TOP=MAX–1,because if that is the case, then the stack is full and no more insertions can be
done. If an attempt is made to insert a value in a stack that is already full, an OVERFLOW

St. Joseph’s College of Engineering 1


CS8391 Data Structures Department of CSE&IT

message is printed.
Example:

Stack After insertion

Algorithm to insert an element in a stack

 Pop Operation
The pop operation is used to delete the topmost element from thestack. However, before
deleting the value, we must first check ifTOP=NULL because if that is the case, then it means
the stack is emptyand no more deletions can be done. If an attempt is made to delete a value
from a stack that is already empty, an UNDERFLOW message is printed

Example:

Stack after Deletion

Algorithm to delete an element from the stack

Peek Operation
Peek is an operation that returns the value of the topmostelement of the stack without deleting
it from the stack.
Example:

Here, the Peek operation will return 5, as it is the value of the topmost element of the stack.

St. Joseph’s College of Engineering 2


CS8391 Data Structures Department of CSE&IT

LINKED REPRESENTATION OF STACK


In a linked stack, every node has two parts—one that stores data and another that stores
theaddress of the next node. The START pointer of the linked list is used as TOP. All insertions
and deletions are done at the node pointed by TOP. If TOP = NULL, then it indicates that the
stack is empty.

Example:

Push Operation
The push operation is used to insert an element into the stack. The new element is added at the
topmost position of the stack

Example: To insert an element with value 9

After insertion

Algorithm to insert an element in a stack

Pop Operation
The pop operation is used to delete the topmost element from astack. However, before deleting
the value, we must first checkif TOP=NULL, because if this is the case, then it means that the
stack is empty and no more deletions can be done.

Example:

St. Joseph’s College of Engineering 3


CS8391 Data Structures Department of CSE&IT

After deletion:

Algorithm to delete an element from the stack

APPLICATION ON STACK

In this section we will discuss typical problems where stacks can be easily applied for a
simpleand efficient solution. The topics that will be discussed in this section include the
following:
 Reversing a list
 Parentheses checker
 Conversion of an infix expression into a postfix expression
 Evaluation of a postfix expression
 Conversion of an infix expression into a prefix expression
 Evaluation of a prefix expression
 Recursion
 Tower of Hanoi

Evaluation of Arithmetic Expressions - Evaluation of a Postfix


Expression
 The ease of evaluation acts as the driving force for computers to translate an infix
notation into a postfix notation. That is, given an algebraic expression written in infix
notation, the computer first converts the expression into the equivalent postfix notation
and then evaluates the postfix expression. Both these tasks—converting the infix
notation into postfix notation and evaluating the postfix expression—make extensive
use of stacks as the primary tool.

 Using stacks, any postfix expression can be evaluated very easily. Every character of the
postfix expression is scanned from left to right. If the character encountered is an
operand, it is pushed on to the stack. However, if an operator is encountered, then the
top two values are popped from the stack and the operator is applied on these values.
The result is then pushed on to the stack.

St. Joseph’s College of Engineering 4


CS8391 Data Structures Department of CSE&IT

Algorithm to evaluate a postfix expression

Example:
infix expression given as 9 – ((3 * 4) + 8) / 4. Evaluate the expression.

The infix expression 9 – ((3 * 4) + 8) / 4 can be written as 9 3 4 * 8 + 4 / – using postfix


notation. Look at Table, which shows the procedure.

Character
Stack
Scanned
9 9
3 9, 3
4 9, 3, 4
* 9, 12
8 9, 12, 8
+ 9, 20 9, 20
4 9, 20, 4
/ 9, 5
- 4
Progra
Conversion of an Infix Expression into a Prefix Expression
Let I be an algebraic expression written in infix notation. I may contain parentheses,
operands,and operators. For simplicity of the algorithm we will use only +, –, *, /, % operators.
The precedence of these operators can begiven as follows:
 Higher priority *, /, %
 Lower priority +, –

Algorithm to convert an infix notation to postfix notation

St. Joseph’s College of Engineering 5


CS8391 Data Structures Department of CSE&IT

Step 1: Add ")" to the end of the infix expression


Step 2: Push "(" on to the stack
Step 3: Repeat until each character in the infix notation is scanned IF a "(" is encountered, push
it on the stackIF an operand (whether a digit or a character) is encountered, add it to the
postfix expression.IF a ")" is encountered, then
 Repeatedly pop from stack and add it to the postfix expression until a "("
isencountered.
 Discard the "(". That is, remove the "(" from stack and do not add it to the postfix
expressionIF an operator is encountered, then
 Repeatedly pop from stack and add each operator (popped from the stack) to the
postfix expression which has the same precedence or a higher precedencethan
 Push the operator to the stack [END OF IF]
Step 4: Repeatedly pop from the stack and add it to the postfix expression until the stack isempty
Step 5: EXIT

Example:
Convert the following infix expressionintopostfixexpression
A – (B / C + (D % E * F) / G)* H)

InfixCharacter Scanned Stack Postfix Expression

(
A ( A
– (– A
( (–( A
B (–( AB
/ (–(/ AB
C (–(/ ABC
+ (–(+ ABC/
( (–(+( ABC/
D (–(+( ABC/D
% (–(+(% ABC/D
E (–(+(% ABC/DE
* (–(+(%* ABC/DE
F (–(+(%* ABC/DEF
) (–(+ ABC/DEF*%
/ (–(+/ ABC/DEF*%
G (–(+/ ABC/DEF*%G
) (– ABC/DEF*%G/+
* (–* ABC/DEF*%G/+
H (–* ABC/DEF*%G/+H
) ABC/DEF*%G/+H*–
QUEUE
A queue is a FIFO (First-In, First-Out) data structure in which the element that is inserted first is

St. Joseph’s College of Engineering 6


CS8391 Data Structures Department of CSE&IT

the first one to be taken out. The elements in a queue are added at one end called the REAR and
removed from the other end called the FRONT. Queues can be implemented by using either
arrays or linked lists. Every queue has front and rear variables that point to the position from
where deletions and insertions can be done, respectively.

ARRAY IMPLEMENTATION OF QUEUE ADT

Front
12 9 7 18 14 36
01
Figure2.4Arrayrepresentationofaqueue

Here,front=0andrear=5.Ifwewanttoaddonemorevaluetothelist,say,ifwewanttoaddanotherelemen
twiththevalue45,thentherearwouldbeincrementedby1andthevaluewouldbestoredatthepositionp
ointedbytherear.Thequeue,aftertheaddition,wouldbeasshowninFig.2.5.

Here,front=0andrear=6.Everytimeanewelementistobeadded,wewillrepeatthesameprocedure.
Front
12 9 7 18 14 36 45
01
Figure2.5Queueafterinsertionofanewelement
Now,ifwewanttodeleteanelementfromthequeue,thenthevalueoffrontwillbeincremented.
Deletionsaredoneonlyfromthisendofthequeue.ThequeueafterthedeletionwillbeasshowninF
ig.2.6.
Front
9 7 18 14 36 45

0 Queueafterdeletionofanelement 89
Figure2.6
However,beforeinsertinganelementinthequeue,wemustcheckforoverflowconditions.Anoverflowo
ccurswhenwetrytoinsertanelementintoaqueuethatisalreadyfull.Aqueueisfullwhenrear=MAX–
1,whereMAXisthesizeofthequeue,thatisMAXspecifiesthemaximumnumberofelementsinthequeue.No
tethatwehavewrittenMAX–1becausetheindexstartsfrom0.
Similarly,beforedeletinganelementfromthequeue,wemustcheckforunderflowconditions.Anunderfl
owconditionoccurswhenwetrytodeleteanelementfromaqueuethatisalreadyempty.Iffront=NULLan
drear=NULL,thenthereisnoelementinthequeue.

Algorithm to insert an element in a queue

Step 1: IF REAR = MAX-1


Write OVERFLOW
Goto step 4
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR =
ELSE
SET REAR = REAR + 1

St. Joseph’s College of Engineering 7


CS8391 Data Structures Department of CSE&IT

[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: EXIT

Algorithm to delete an element from a queue


Step 1: IF FRONT = -1 OR FRONT > REAR
Write UNDERFLOW
ELSE
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT
SET VAL = QUEUE[FRONT]

LINKED REPRESENTATION OF QUEUE ADT

 We have seen how a queue is created using an array. Although this technique of creating a
queue is easy, its drawback is that the array must be declared to have some fixed size. If we
allocate space for 50 elements in the queue and it hardly uses 20–25 locations, then half of
the space will be wasted. And in case we allocate less memory locations for a queue that
might end up growing large and large, then a lot of re-allocations will have to be done,
thereby creating a lot of overhead and consuming a lot of time.
 In case the queue is a very small one or its maximum size is known in advance, then the
array implementation of the queue gives an efficient implementation. But if the array size
cannot be determined in advance, the other alternative, i.e., the linked representation is
used.
 In a linked queue, every element has two parts, one that stores the data and another that
storesthe address of the next element. The START pointer of the linked list is used as
FRONT. Here, we willalso use another pointer called REAR, which will store the address of
the last element in the queue.
 All insertions will be done at the rear end and all the deletions will be done at the front
end. If
 FRONT = REAR = NULL, then it indicates that the queue is empty.

Insert Operation
The insert operation is used to insert an element into a queue. The new element is added as the
last element of the queue.

Algorithm to insert an element in a linked queue

St. Joseph’s College of Engineering 8


CS8391 Data Structures Department of CSE&IT

Linked queue after inserting a new node

Delete Operation
The delete operation is used to delete the element that is first inserted in a queue, i.e., the
element whose address is stored in FRONT. However, before deleting the value, we must first
check if FRONT=NULL because if this is the case, then the queue is empty and no more
deletions can be done.

St. Joseph’s College of Engineering 9


CS8391 Data Structures Department of CSE&IT

Linked queue after deletion of an element

TYPES OF QUEUES
A queue data structure can be classified into the following types:
1. Circular Queue
2. Dequeue
3. Priority Queue
4. Multiple Queue

CIRCULAR QUEUE
In linear queues, we have discussed so far that insertions can be done only at one end called the
REAR and deletions are always done from the other end called the FRONT.
54 9 7 18 14 36 45 21 99 72

Q[0]
Al Q[6] Q[1]

Q[5] Q[2]
Q[4] Q[3]

Insert an element in a circular queue


Step 1: IF FRONT = and Rear = MAX - 1
Write OVERFLOW
IF FRONT = -1 and REAR = -1
SET FRONT = REAR =
ELSE IF REAR = MAX - 1 and FRONT !=
SET REAR =
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT
 If front = –1, then there are no elements in the queue. So, an underflow condition will be
reported.

St. Joseph’s College of Engineering 10


CS8391 Data Structures Department of CSE&IT

 If the queue is not empty and front = rear,then after deleting the element at the front the
queue becomes empty and so front and rear are set to –1. This is illustrated in Fig. 8.21.
 If the queue is not empty and front = MAX–1,then after deleting the element at the
front,frontis set to 0.

Empty queue

Queue with a single element

Queue where FRONT = MAX–1 before deletion

DEQUEUE
 A deque (pronounced as ‘deck’ or ‘dequeue’) is a list in which the elements can be
inserted or deleted at either end.
 It is also known as a head-tail linked list because elements can be added to or removed
from either the front (head) or the back (tail) end.
 However, no element can be added and deleted from the middle.
 In the computer’s memory, a deque is implemented using either 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.
 The elements in a deque extend from the LEFT end to the RIGHT end and since it is
circular, Dequeue[N–1] is followed by Dequeue[0].

There are two variants of a double-ended queue. They include


 Input restricted deque - In this dequeue,insertions can be done only at one of the
ends,while deletions can be done from both ends.
 Output restricted deque - In this dequeue deletions can be done only at one of the
ends,while insertions can be done on both ends.

PRIORITY QUEUE

St. Joseph’s College of Engineering 11


CS8391 Data Structures Department of CSE&IT

Apriorityqueueisadatastructureinwhicheachelementisassignedapriority.Thepriorityofthe
elementwillbeusedtodeterminetheorderinwhichtheelementswillbeprocessed.Thegeneral rules of
processing the elements of a priority queueare
 An element with higher priority is processed before an element with a lowerpriority.
 Twoelementswiththesamepriorityareprocessedonafirst-come-first-served(FCFS)basis.
Apriorityqueuecanbethoughtofasamodifiedqueueinwhichwhenanelementhastoberemoved
fromthequeue,theonewiththehighest-priorityisretrievedfirst.Thepriorityoftheelementcan be set
based on various factors. Priority queues are widely used in operating systems toexecutethe
highest priority process first. The priority of the process may be set based on the CPU time it
requires to get executed completely.
For example, if there are three processes, where the first process needs 5 ns to complete, the
second process needs 4 ns, and the third process needs 7 ns, then the second process will have
the highest priority and will thus be the first to be executed.
However,CPUtimeisnottheonlyfactorthatdeterminesthepriority,ratheritisjustoneamong
severalfactors.Anotherfactoristheimportanceofoneprocessoveranother.

Implementation of a Priority Queue


There are two ways to implement a priority queue. We can either use a sorted list to
store the elementssothatwhenanelementhastobetakenout,thequeuewillnothavetobesearchedfor
the element with the highest priority or we can use an unsorted list so that insertions are always
doneattheendofthelist.Everytimewhenanelementhastoberemovedfromthelist,theelement
withthehighestprioritywillbesearchedandremoved.

Linked Representation of a Priority Queue


In the computer memory, a priority queue can be represented using arrays or linked lists.
When apriorityqueueisimplementedusingalinkedlist,theneverynodeofthelistwillhavethreeparts:
(a)theinformationordatapart,
(b)theprioritynumberoftheelement
(c)theaddressofthe next element.
If we are using a sorted linked list, then the element with the higher priority will
precede the element with the lowerpriority.Consider the priority queue shown in Fig

A1 B2 C3 D3 E4
F 5 X
Lower priority number means higher priority. For example, if there are two elements Aand
B, where Ahas apriority number1and Bhasaprioritynumber 5,thenAwillbe processedbefore B
as it has higher priority thanB.
ThepriorityqueueinFig.8.25isasortedpriorityqueuehavingsixelements.Fromthequeue, we
cannot make out whether A was inserted before E or whether E joined the queue before A
because the list is not sorted based on FCFS. Here, the element with a higher priority comes
before the element with a lower priority. However, we can definitely say that C was inserted in
the queue before Dbecause when two elements have the same priority the elements are
arranged and processed on FCFSprinciple.

Insertion:When a new element has to be inserted in a priority queue, we have to traverse the
entirelistuntilwefindanodethathasaprioritylowerthanthatofthenewelement.Thenewnode is

St. Joseph’s College of Engineering 12


CS8391 Data Structures Department of CSE&IT

inserted before the node with the lower priority. However, if there exists an element that has
thesamepriorityasthenewelement,thenewelementisinsertedafterthatelement.

A1 B2 C3 D5 E 6 X

Ifwehavetoinsertanewelementwithdata=Fandprioritynumber=4,thentheelementwillbe
insertedbeforeDthathasprioritynumber5,whichislowerprioritythanthatofthenewelement. So, the
priority queue now becomes as shown in the following Fig.
A1 B2 C3 F4 D5 E 6 X

However,ifwehaveanewelementwithdata=Fandprioritynumber=2,thentheelementwill be
inserted after B, as both these elements have the same priority but the insertions are done on
FCFS basis as shown in Fig.8.28.
A1 B2 F2 C3 D5 E 6 X

Figure 8.28 Priority queue after insertion of a new node

Deletion: Deletion is a very simple process in this case. The first node of the list will be deleted
and the data of that node will be processed first

Array Representation of a Priority Queue


Whenarraysareusedtoimplementapriorityqueue,thenaseparatequeueforeachprioritynum
ber ismaintained.Eachofthesequeueswillbeimplementedusingcirculararraysorcircularqueues.
Everyindividualqueue will have itsownFRONTandREARpointers. Weuseatwo-
dimensionalarrayforthispurposewhereeachqueuewillbeallocatedthesame amount of space.
Look at the two-dimensional representation of a priority queue given below. Given the
FRONT and REAR values of each queue, the two-dimensional matrix can be formed as shown
in Fig.

FRONT[K]andREAR[K]containthefrontandrearvaluesofrowK,whereKistheprioritynumber.
Note that here we are assuming that the row and column indices start from 1, not 0. Obviously,
while programming, we will not take suchassumptions.
Insertion - To insert a new element with priority K
inthepriorityqueue,addtheelementattherearend of row K, where K is the row number as well as
the priority number of that element. For example, ifwe have to insert an element R with priority
number 3, thenthepriorityqueuewillbegivenas

St. Joseph’s College of Engineering 13


CS8391 Data Structures Department of CSE&IT

Deletion - To delete an element, we find the first nonempty queue and then process the front
element of the first non-empty queue. In our priority queue, the first non-empty queue is the
one with priority number 1 and the front element is A, so A will be deleted and processed first.
In technical terms, find the element with the smallest K, such that FRONT[K] != NULL.

APPLICATIONS OFQUEUES
 Queuesarewidelyusedaswaitinglistsforasinglesharedresourcelikeprinter,disk,CPU.
 Queues are used to transfer data asynchronously (data not necessarily received
atsamerate as sent) between two processes (IO buffers), e.g., pipes, file IO,sockets.
 Queues are used as buffers on MP3 players and portable CD players, iPodplaylist.
 QueuesareusedinPlaylistforjukeboxtoaddsongstotheend,playfromthefrontofthelist.
 Queuesareusedinoperatingsystemforhandlinginterrupts.Whenprogrammingareal-
time system that can be interrupted, for example, by a mouse click, it is necessary to
processthe interrupts immediately, before proceeding with the current job. If the
interrupts have to be handled in the order of arrival, then a FIFO queue is the
appropriate datastructure.

JOSEPHUS PROBLEM
Let us see how queues can be used for finding a solution to the Josephus problem.
InJosephusproblem,npeoplestandinacirclewaitingtobeexecuted.Thecountingstartsatsome
point in the circle and proceeds in a specific direction around the circle. In each step, a certain
number of people are skipped and the next person is executed (or eliminated). The
elimination of people makes the circle smaller and smaller. At the last step, only one person
remains who is declared the ‘winner’.
Therefore,iftherearennumberofpeopleandanumberkwhichindicatesthatk–1peopleare
skipped and k–th person in the circle is eliminated, then the problem is to choose a position in
the initial circle so that the given person becomes the winner.
For example, if there are 5 (n) people and every second (k) person is eliminated, then first the
person at position 2 is eliminated followed by the person at position 4 followed by personat
position 1 and finally the person at position 5 is eliminated. Therefore, the person at position 3
becomes the winner.

St. Joseph’s College of Engineering 14


CS8391 Data Structures Department of CSE&IT

St. Joseph’s College of Engineering 15

You might also like