0% found this document useful (0 votes)
4 views35 pages

StackQueue MCH

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

STACKS

Dr. Maumita Chakraborty


University of Engineering and Management Kolkata
Introduction to Stacks

A linear data structure which can be implemented either using an array


or a linked list.
The elements in a stack are added and removed only from one end,
which is called top.
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.

Another plate
will be added on
The topmost plate
top of this plate
will be removed first
•In computer’s memory stacks can be represented as a
linear array.
•A variable TOP used to store the address of the topmost
element of the stack. It is this position from where the
element will be added or deleted.
•Variable MAX used to store the maximum number of
elements that the stack can hold.
•If TOP = NULL, then the stack is empty and if TOP = MAX-
1, then the stack is full.
 Used to insert an element in to the stack.
 The new element is added at the topmost position of the stack.
 If TOP=MAX-1, the stack is full and no more insertions possible, and an
OVERFLOW message is printed.
1 2 3 4 5

0 1 2 3 TOP = 4 5 6 7 8 9

1 2 3 4 5 6

0 1 2 3 4 TOP = 5 6 7 8 9

Algorithm to PUSH an element in to the stack

Step 1: IF TOP = MAX-1, then


Step 2: PRINT “OVERFLOW”
Step 3: Go to Step 7
Step 4: [END OF IF]
Step 5: SET TOP = TOP + 1
Step 6: SET STACK[TOP] = VALUE
Step 7: END
 Used to delete the topmost element from the stack.
 If TOP = -1, the stack is empty, so no more deletions possible, an
UNDERFLOW message is printed.

1 2 3 4 5

0 1 2 3 TOP = 4 5 6 7 8 9

1 2 3 4

0 1 2 TOP = 3 4 5 6 7 8 9

Algorithm to POP an element from the stack

Step 1: IF TOP = -1, then


Step 2: PRINT “UNDERFLOW”
Step 3: Go to Step 7
Step 4: [END OF IF]
Step 5: SET VAL = STACK[TOP]
Step 6: SET STACK[TOP] = -1 //default value
Step 7: SET TOP = TOP - 1
Step 8: RETURN VAL
Step 9: END
 An operation that returns the value of the topmost element of the stack without
deleting it from the stack.
 If TOP = -1, then an appropriate message is printed else the value is returned.

1 2 3 4 5

0 1 2 3 TOP = 4 5 6 7 8 9

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

Algorithm for Peep Operation

Step 1: IF TOP = -1, then


Step 2: PRINT “STACK IS EMPTY”
Step 3: Go TO Step 5
Step 4: RETURN STACK[TOP]
Step 5: END
Algorithm to PUSH an element in to a linked stack

Step 1: Allocate memory for the new node and name it as New_Node
Step 2: SET New_Node->DATA = VAL
Step 3: IF TOP = NULL, then
Step 4: SET New_Node->NEXT = NULL
Step 5: SET TOP = New_Node
Step 6: ELSE
Step 7: SET New_node->NEXT = TOP
Step 8: SET TOP = New_Node
Step 9: [END OF IF]
Step 10: END

1 7 3 4 2 6 5 X

TOP

9 1 7 3 4 2 6 5 X

TOP, New_Node
Algorithm to POP an element from the stack

Step 1: IF TOP = NULL, then


Step 2: PRINT “UNDERFLOW”
Step 3: Go To Step 9
Step 4: [END OF IF]
Step 5: SET PTR = TOP
Step 6: SET TOP = TOP ->NEXT
Step 7: PTR->NEXT = NULL
Step 8: FREE PTR
Step 9: END

9 1 7 3 4 2 6 5 X

TOP, PTR

1 7 3 4 2 6 5 X

TOP
Applications
 Conversion of Infix to Postfix Expression
 Infix Notation: X + Y (Operators are written between their
operands)
 Postfix Notation: X Y + (Operators are written after their
operands). Also known as Reverse Polish Notation.
 Evaluation of a Postfix Expression
 E.g. Expressions like 4 5 6 * + can be evaluated easily.
 Recursion
 A function calling itself again and again breaking a
problem down into smaller and smaller subproblems, until
we get a small enough problem that can be solved
trivially.
Infix to Postfix Conversion Using Stack

Infix Expression:
A+ (B*C-(D/E^F)*G)*H
Algorithm to convert Infix To Postfix
X be an input infix expression and Y the equivalent postfix output.
1. Push “(“onto Stack, and add “)” to the end of X.
2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack
is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
6. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which
has the same precedence as or higher precedence than operator.
7. Add operator to Stack.
8. End of If
9. If a right parenthesis is encountered ,then:
10. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a
left parenthesis is encountered.
11. Remove the left Parenthesis.
12. End of If
13. End of If
14. END.
Evaluating Postfix Expression using Stack

1) Create a stack to store operands


(or values).
2) Scan the given expression and do
following for every scanned
element.
…..a) If the element is a number,
push it into the stack
…..b) If the element is a operator,
pop operands for the operator from
stack. Evaluate the operator and
push the result back to the stack
3) When the expression is ended, the
number in the stack is the final
answer
Recursion
 Function that calls itself during execution.
 Each time any recursive function calls itself, the size of the problem
is reduced.
 Direct recursion: Calls itself repeatedly until it reaches the last
executive statement, i.e. base value. Base value is given and total
final value is based on base value.
 Indirect recursion: Function calls another function, which calls the
first function.

A() B()
{ {
…… ……

B() A()
…… ……
} }
Limitations of Recursion
 Recursive algorithm should be logarithmic in their
execution.
 Linear list (linked list) has O(n) efficiency. So, linked list is not
good for recursion.
 Works best when algorithm uses a data structure that
supports recursion.
 E.g.- Trees.
 Runs slower than its non-recursive equivalent.
 Number of recursive calls may lead to a possibility of out
of memory situation.
 Iterative function uses linear time i.e. O(n), Recursive
function uses logarithmic time or exponential time, i.e.
O(log n) or O(kn).
Recursion vs. Iteration
 Advantages of Iteration:  Advantages of
 Works well with linear Recursion:
data structure.  Solution shorter, simpler,
 Uses less memory. more understandable.
 Handles large numbers.  Does not use any loop.
 Space requirement fixed  Time to develop and
[recursion requires more remove bugs less than
storage space]. iteration.
 Uses linear time, O(n)  Trees naturally recursive.
[less than recursion].  Recursion works better
than iteration for fewer
number of recursive
calls.
Recursion Tree
 First function call is assumed to be its root and all its
other nodes in sequence represent corresponding
recursive calls.
 Each vertex/node assumed to be an instruction.
 Leaves represent base case of recursion.
 Key tool for analysis of recursive algorithm.
 Memory and time requirement of recursive program
depend on height and size of recursion tree.
 Total number of instructions handled by program
calculated from number of non-leaf vertices of tree.
 Each recursive function calls the next level.
Recursion Tree - Examples
 Recursion tree is a
chain if
 If it is simple, linear and
has one vertex in each
level.
 Each vertex has only one
child.
 Each child corresponds
to one single recursive
call that occurs.
 Transformation from
recursion to iteration
easy and saves time and
space.
Recursion Tree - Examples
 Recursion tree with many
vertices:
 Signify duplicate tasks.
 Each vertex with more than
one child corresponds to a
recursive call.
 One instruction printed for
each vertex in tree, except
for leaves.
 Number of recursive calls in
a tree of n nodes is 2n –
1.
 Sets up a stack to use while
traversing the tree.
Tail Recursion
 Last executed statement of any recursive function
becomes a recursive call to that function.
 Special type of recursion which guarantees that
nothing is left to be executed in the function after the
recursive call.
 Recursive call should be the last statement and
there should be no earlier recursive calls, whether
direct or indirect.
 Advantages:
 Smart compilers can detect tail recursion and convert it to
iteration to optimize code.
 Used to implement loops in languages that do not support
loop structures explicitly, e.g. – Prolog.
Tail Recursion-Example (Factorial of a
number)
 int fact(int x)  int fact(int x)
 {  {
 if(x==0)  return fact_aux(x,1);
 return 1;  }
 else
 int fact_aux(int x, int rslt)
 return x*fact(x-1);
 {
 }
 if(x==1)
 return rslt;
 return fact_aux(x-
1,x*rslt);
 }
Towers of Hanoi
 64 disks of decreasing sizes from bottom to top.
 3 towers, A(first), B(middle), C(end).
 Moves all disks from tower A to C, following the
conditions below:
 Only one disk can be moved at a time.
 A larger disk must never be placed over smaller.
 One tower can be used for intermediate storage of disks.
Towers of Hanoi
Algorithm
Hanoi(disk,source,dest,aux)
1. Begin
2. If disk=1, then
3. Move disk from source to dest
4. Else
5. Hanoi(disk-1,source,aux,dest) //Step 1
6. Move disk from source to dest //Step 2
7. Hanoi(disk-1,aux,dest,source) //Step 3
8. Endif
9. Return
10. End
QUEUES
 Data structure which stores its elements in an ordered manner. Take for
example the analogies given below:

 People moving on an escalator. The people who got on the escalator first
will be the first one to step out of it.
 People waiting for bus. The first person standing in the line will be the first
one to get into the bus.
 A queue is a FIFO (First In First Out) data structure in which the element that
was 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 one end called front.
 Every queue will have front and rear variables that will point
to the position from where deletions and insertions can be
done respectively.
 Consider a queue shown in figure

12 9 7 18 14 36

0 1 2 3 4 5 6 7 8 9

•Here, front = -1 and rear = 5.


• Adding one more value in the list say with value 45, then rear would be
incremented by 1 and the value would be stored at the position pointed
by rear.
•The queue after addition would be as shown in figure

12 9 7 18 14 36 45

0 1 2 3 4 5 6 7 8 9
 Here, front = -1 and rear = 6.
 Now, deleting an element from the queue, the value of front will be incremented.
The queue after deletion will be as shown in figure

9 7 18 14 36 45

0 1 2 3 4 5 6 7 8 9

•Here, front = 0 and rear = 6.


•Before insertion in the queue overflow condition must be checked.
•Overflow occurs when insertion tried into an already full queue.
•Queue is full when Rear = MAX – 1, (MAX being the size of the queue i.e., MAX
specifies the maximum number of elements that the queue can hold).

Before deletion from the queue underflow condition must be checked.


Underflow occurs when deletion tried from an already empty queue.
If front = -1 and rear = -1, this means there is no element in the queue.
Algorithm to insert an element in the queue
Step 1: IF REAR=MAX-1, then
Step 2: Write OVERFLOW, Go To Step 10
Step 3: [END OF IF]
Step 4: ELSE
Step 7: SET REAR = REAR + 1
Step 8: SET QUEUE[REAR] = NUM
Step 9: [END OF IF]
Step 10: Exit

Algorithm to delete an element from the queue

Step 1: IF FRONT = REAR, then


Step 2: Write UNDERFLOW, Go To Step 7
Step 3: ELSE
Step 4: SET FRONT = FRONT + 1
Step 5: SET VAL = QUEUE[FRONT]
Step 6: [END OF IF]
Step 7: Exit
7 18 14 36 45 21 99 72

0 1 2 3 4 5 6 7 8 9

Here, front = 1 and rear = 9.


Although there is space, still no insertion can be done as rear = MAX – 1,
and OVERFLOW has occurred.
Major drawback of a linear queue. Leads to wastage of space.

Solutions:
1. Shifting elements to left so that the vacant space can be occupied and
utilized efficiently. Very time consuming (especially when the queue is
quite large).

2. Using a circular queue. In circular queue, the first index comes right
after the last index.
•During insertion, rear incremented as
Q[0]
Q[6] Q[1]
rear=(rear+1) mod MAX

Q[2]
•During deletion, front incremented as
Q[5]
front=(front+1) mod MAX
Q[4] Q[3] • After MAX-1, rear goes to 0, if space available.
If rear != MAX – 1, then the value will be inserted and rear will be incremented as
illustrated in figure
90 49 7 18 14 36 45 21
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 there as shown in figure
7 18 14 36 45 21 99 72
0 1 Front=2 3 4 5 6 7 8 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. This is shown in figure
72 63 9 18 27 39 81
0 1 2 3 4 rear= 5 6 7 8 front= 9
Algorithm to insert an element in circular queue
Step 1: INITIALIZE REAR to 0, FRONT to 0
Step 2: IF (FRONT=REAR+1) or (REAR=MAX-1 and FRONT=-1), then
Step 3: Write OVERFLOW, Go To Step 8
Step 4: ELSE
Step 5: SET REAR = (REAR+1)mod(MAX)
Step 6: SET QUEUE[REAR] = NUM
Step 7: END IF
Step 8: Exit

Algorithm to delete an element from circular queue


Step 1: IF (FRONT = REAR) then
Step 2: Write UNDERFLOW, Go to Step 8
Step 3: ELSE
Step 4: SET FRONT = (FRONT+1)mod(MAX)
Step 5: SET ITEM = QUEUE[FRONT]
Step 6: RETURN ITEM
Step 7: END IF
Step 8: Exit
 Every element has two parts- one that stores data and the other that stores
the address of the next element.
 The START pointer of the linked list is used as FRONT.
 Another pointer called REAR stores the address of the last element in the
queue.
 All insertions done at the rear end and all the deletions done at the front
end.
 If FRONT = REAR = NULL, then it indicates that the queue is empty.

1 7 3 4 2 6 5 X

FRONT REAR

Insert 1 7 3 4 2 6 5 9 X
Operation REAR
FRONT

Delete 5
7 3 4 2 6 9 X
Operation
REAR
FRONT
Insertion and Deletion in Linked Queue
Algorithm to insert an element into a linked queue
Step 1: Allocate memory for the new node and name it as PTR
Step 2: SET PTR->DATA = VAL
Step 3: IF FRONT = NULL, then
Step 4: SET FRONT = REAR = PTR;
Step 5: SET FRONT->NEXT = REAR->NEXT = NULL
Step 6: ELSE
Step 7: SET REAR->NEXT = PTR
Step 8: SET REAR = PTR
Step 9: SET REAR->NEXT = NULL
Step 10: [END OF IF]
Step 11: END

Algorithm to delete an element from a linked queue


Step 1: IF FRONT = NULL, then
Step 2: Write “Underflow”
Step 3: Go to Step 12
Step 4: [END OF IF]
Step 5: SET PTR = FRONT
Step 6: FRONT = FRONT->NEXT
Step 7: IF FRONT = NULL
Step 8: REAR = NULL
Step 9: END IF
Step 10: PTR->NEXT = NULL
Step 11: FREE PTR
Step 12: END
 A queue in which elements can be inserted or deleted at either end.
 Two variants of a double ended queue are:
 Input restricted deque: Insertions can be done only at rear while deletions
can be done from both the ends.
 Output restricted deque: Deletions can be done only from front while
insertions can be done on both the ends.
 An abstract data type in which each element is assigned a priority.
 The priority of the element 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:
 An element with higher priority is processed before an element with
lower priority.
 Two elements with same priority are processed on a first come first
served (FCFS) basis.
 A modified queue in which the highest-priority one is retrieved first. The
priority of the element can be set based upon distinct factors.
 Widely used in operating systems to execute the highest priority process
first. The priority of the process may be set based upon the CPU time it
needs to get executed completely.

You might also like