Stack Adt: CS8391 Data Structures Department of CSE&IT
Stack Adt: CS8391 Data Structures Department of CSE&IT
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
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
message is printed.
Example:
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:
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.
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
After insertion
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:
After deletion:
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
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.
Example:
infix expression given as 9 – ((3 * 4) + 8) / 4. Evaluate the expression.
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 +, –
Example:
Convert the following infix expressionintopostfixexpression
A – (B / C + (D % E * F) / G)* H)
(
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
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.
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.
[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: EXIT
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.
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.
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]
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
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].
PRIORITY QUEUE
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.
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
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
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
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
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.