You are on page 1of 48

Stack

Data Structures

1
Stack
Stack is a linear data structure which follows a
particular order in which the operations are
performed.
Insertion of element into stack is called PUSH and
deletion of element from stack is called POP.
The order is LIFO(Last In First Out)

2
Representation of Stack in Memory
The stack can be implemented into two
ways:

◦ Using arrays (Static implementation)


◦ Using pointer (Dynamic implementation)

3
Operation on Stacks:
Stack( ): It creates a new stack that is empty. It
needs no parameter and returns an empty stack.
push(item): It adds a new item to the top of the
stack.
pop( ): It removes the top item from the stack.
peek( ): It returns the top item from the stackbut
does not remove it.
isEmpty( ): It tests whether the stack is empty.
size( ): It returns the number of items on the stack.

4
Stack Conditions

5
PUSH Operation
The process of adding one element or item tothe
stack is represented by an operation called as
the PUSH operation.

6
PUSH Operation:
The process of adding one element or item to the stack is
represented by an operation called as the PUSH operation.
The new element is added at the topmost position of the stack.
ALGORITHM:
PUSH (STACK, TOP, SIZE, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of the
element of the array. ITEM to be inserted.
Step 1: if TOP = N then [Check Overflow]
PRINT “ STACK is Full or Overflow”
Exit
[End if]
Step 2: TOP = TOP + 1 [Increment the TOP]
Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
7
POP Operation
The process of deleting one element or item from
the stack is represented by an operation called as
the POP operation.
When elements are removed continuously from a
stack, it shrinks at same end i.e., top

8
POP Operation
The process of deleting one element or item from the stack
is represented by an operation called as the POP
operation.
ALGORITHM: POP (STACK, TOP)
STACK is the array with N elements. TOP is the pointer to the top of the
element of the array.
Step 1: if TOP = -1 then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit
[End if]
Step 2: ITEM = STACK[TOP] [copy the TOP Element]
Step 3: TOP = TOP - 1 [Decrement the TOP]
Step 4: Return

9
PEEK Operation
The process of returning the top item from the
stack but does not remove it called as the POP
operation.

ALGORITHM: PEEK (STACK, TOP)


STACK is the array with N elements. TOP is the pointer to
the top of the element of the array.
Step 1: if TOP = NULL then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit
[End if]
Step 2: Return (STACK[TOP] [Return the top
element of the stack]
Step 3:Exit
10
Application of Stacks
It is used to reverse a word. You push a given word to stack
– letter by letter and then pop letter from the stack.
“Undo” mechanism in text editor.
Backtracking: This is a process when you need to access
the most recent data element in a series of elements. Once
you reach a dead end, you must backtrack.
Language Processing: Compiler’ syntax check for matching
braces is implemented by using stack.
Conversion of decimal number to binary.
To solve tower of Hanoi.
Conversion of infix expression into prefix and postfix.
Quick sort

11
Infix, Postfix and Prefix
Expression
Infix Expression: An expression in which the
operator is in between its two operands.
A+B
Prefix Expression: An expression in which operator
precedes its two operands is called an prefix
expression.
+AB
Postfix Expression: An expression in which
operator follows its two operands is called a postfix
expression.
AB+
12
Infix to Postfix Conversion

Infix expression can be directly evaluated but


the standard practice in CS is that the infix
expression converted to postfix form and then
the expression is evaluated. During both
processes stack is proved to be a useful data
structure.

13
Infix to Postfix By-Hand
Algorithm
1. Given a expression in the infix form.
2. Find the highest precedence operator
3. If there are more then one operators with the same
precedence check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to postfix
A+ B --> A B+
5. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.

14
Infix to Prefix By-Hand
Algorithm
1. Given a expression in the infix form.
2. Find the highest precedence operator
3. If there are more then one operators with the same
precedence check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to prefix
A+ B --> +A B
5. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.

15
C language operators Precedence
and Associativity

16
Infix to Postfix Step by Step
Conversion
● A+B*C-D (Infix) ● (A+B)*C-D (Infix)
● A+BC*-D ● (AB+)*C-D
● ABC*+-D ● AB+C*-D
● ABC*+D- (Postfix) ● AB+C*D- (Postfix)

Exercise:
1. Infix ( (A * B) + (C / D) ) to Postfix
2. Infix ((A * (B + C) ) / D) to Postfix
3. Infix (A * (B + (C / D) ) ) to Postfix
17
Infix to Prefix Step by Step
Conversion
● A*B+C/D (Infix) ● A*(B+C/D)
● *AB+C/D ● A*(B+/CD)
● *AB+/CD ● A*(+B/CD)
● +*AB/CD (Prefix) ● *A+B/CD

Exercise:
1. Infix ( (A * B) + (C / D) ) to Prefix
2.Infix ((A * (B + C) ) / D) to Prefix
3.Infix (A * (B + (C / D) ) ) to Prefix
18
Algorithm for Infix to Postfix using
stack_1
RPolish (Q, P)
Suppose Q is an arithmetic expression written in infix notation. This algorithm
finds the equivalent postfix expression P.
Step 1: Push ‘(‘ onto stack and add ‘)’ to the end of Q.
Step 2: Scan Q from left to right and repeat step 3 to 6 for each element of Q
until the stack is empty.
Step 3: If an operand is encountered add it to P.
Step 4: If a left parenthesis is encountered, push it onto stack.
Step 5: If an operator ◘ is encountered then:
(a) Repeatedly pop from STACK and add to P each operator (on the top of the
STACK) which has the same precedence or higher precedence than ◘.
(b) Add ◘ to STACK.
[End of If structure] 19
Infix to Postfix using stack _2
Step 6: If a right parenthesis is encountered than
(a) Repeatedly pop from STACK and add to P each operator (on the top
of STACK) until a left parenthesis is encountered.
(b) Remove the left parenthesis (Do not add the left parenthesis to P).
[End of If structure]
[End of step 2 loop]
Step 7: Exit.

20
Infix to Postfix using stack
Example A*B+C become AB*C+
(A*B+C)

Current STACK Output (P)


Symbol
( ( -
A ( A
* (* A
B (* AB
+ (+ AB*
C (+ AB*C
) - AB*C+

21
Infix to Postfix using stack ...
● Example A * (B + C * D) + E becomes A B C D * + * E +
(A*(B+C*D)+E)
Current Symbol Stack Output
( ( -
A ( A
* (* A
( (*( A
B (*( AB
+ (*(+ AB
C (*(+ ABC
* (*(+* ABC
D (*(+* ABCD
) (* ABCD*+
+ (+ ABCD*+*
E (+ ABCD*+*E
) - ABCD*+*E+ 22
Algorithm for Infix to Prefix
Polish (Q, P)
Suppose Q is an arithmetic expression written in infix notation. This algorithm
finds the equivalent prefix expression P.
Step 1: Reverse the input string
Step 2: Push ‘(‘ onto stack and add ‘)’ to the end of Q.
Step 3: Scan Q from left to right and repeat step 4 to 7 for each element of Q until
the stack is empty.
Step 4: If an operand is encountered add it to P.
Step 5: If a left parenthesis is encountered, push it onto stack.
Step 6: If an operator ◘ is encountered then:
(a) Repeatedly pop from STACK and add to P each operator (on the top of the
STACK) which has the same precedence or higher precedence than ◘.
(b) Add ◘ to STACK.
23
[End of If structure]
Algorithm for Infix to Prefix
Step 7: If a right parenthesis is encountered than
(a) Repeatedly pop from STACK and add to P each operator (on the top
of STACK) until a left parenthesis is encountered.
(b) Remove the left parenthesis (Do not add the left parenthesis to P).
[End of If structure]
[End of step 2 loop]
Step 7: Reverse the output to get the required prefix.
Step 8: Exit

24
Infix to Prefix using stack ...
Infix: A+(B*C-(D/E^F)*G)*H
Enclose the Expression in ‘()’ (A+(B*C-(D/E^F)*G)*H)
Reverse the string (H*(G*(F^E/D)-C*B)+A)

Current Symbol Stack Output (P)


( ( -
H ( H
* (* H
( (*( H
G (*( HG
* (*(* HG
( (*(*( HG
F (*(*( HGF
^ (*(*(^ HGF
E (*(*(^ HGFE
/ (*(*(/ HGFE^
D (*(*(/ HGFE^D
25
Infix to Prefix using stack ...
Current Symbol Stack Output (P)
) (*(* HGFE^D/
- (*(- HGFE^D/*
C (*(- HGFE^D/*C
* (*(-* HGFE^D/*C
B (*(-* HGFE^D/*CB
) (* HGFE^D/*CB*-
+ (+ HGFE^D/*CB*-*
A (+ HGFE^D/*CB*-*A
) - HGFE^D/*CB*-*A+

26
Evaluating Arithmetic Postfix
Expression
● Expression is available in the postfix form
● Initialize the stack of operands.
● While expression has more token (operators and operands), do
– If the next token is an operand
● Push it on the stack
– Else the token is an operator
● Pop two operands from the stack

● Apply the operator to the operands

● Push the result back on to the stack

– End If
● End While
● Result of expression is on the operand stack, pop and display.
27
Evaluating Arithmetic Postfix
Expression
PostFix Expression 2 3 4 + * 5*
Move Token Stack
1 2 2
2 3 23
3 4 234
4 + 2 7 (3+4=7)
5 * 1 4 (2*7=14)
6 5 14 5
7 * 70 (14*5=70)

28
Recursion

29
Ex. 1: The Handshake Problem

There are n people in a room. If each person shakes


hands once with every other person. What is the total
number h(n) of handshakes?

h(n) = h(n-1) + n-1 h(4) = h(3) + 3 h(3) = h(2) + 2 h(2) = 1

h(n): Sum of integer from 1 to n-1 = n(n-1) / 2 30


Recursion

In some problems, it may be natural to


define the problem in terms of the problem
itself.
Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!

31
Example 2: factorial function

In general, we can express the factorial


function as follows:
n! = n * (n-1)!
Is this correct? Well… almost.
The factorial function is only defined for positive
integers. So we should be a bit more precise:
n! = 1 (if n is equal to
1)
n! = n * (n-1)! (if n is larger
than 1)

32
factorial function

The C++ equivalent of this definition:


int fac(int numb){
if(numb<=1)
return 1;
else
return numb * fac(numb-1);
}
recursion means that a function calls itself

33
factorial function

Assume the number typed is 3, that is, numb=3.


fac(3) :
3 <= 1 ? No.
fac(3) = 3 * fac(2)
fac(2) :
2 <= 1 ? No.
fac(2) = 2 * fac(1)

fac(1) :
1 <= 1 ? Yes.
return 1
int fac(int numb){
fac(2) = 2 * 1 = 2 if(numb<=1)
return fac(2) return 1;
else
fac(3) = 3 * 2 = 6 return numb * fac(numb-1);
return fac(3) }
fac(3) has the value 6
34
The Towers of Hanoi

35
A Legend
Legend has it that there were three diamond needles set
into the floor of the temple of Brahma in Hanoi.

Stacked upon the leftmost needle were 64 golden disks,


each a different size, stacked in concentric order:

36
A Legend (Ct’d)
The priests were to transfer the disks from the first
needle to the second needle, using the third as
necessary.

But they could only move one disk at a time, and could
never put a larger disk on top of a smaller one.
When they completed this task, the world would end!
37
To Illustrate

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

Since we can only move one disk at a time, we move the


top disk from A to B.

38
Example

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from A to C.

39
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from B to C.

40
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from A to B.

41
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from C to A.

42
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from C to B.

43
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

We then move the top disk from A to B.

44
Example (Ct’d)

For simplicity, suppose there were just 3 disks, and


we’ll refer to the three needles as A, B, and C...

and we’re done!


The problem gets more difficult as the number of disks
increases...
45
Take an example for 3 disks : Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.

Step 1 : Shift 'A' to 'B'.


Step 2 : Shift 'A' to 'C'.
Step 3 : Shift 'B' to 'C'.
Step 4 : Shift ‘A' to ‘B'.
Step 5 : Shift ‘C' to ‘A'.
Step 6 : Shift ‘C' to ‘B'.
Step 7 : Shift ‘A' to ‘B'.

The pattern here is :


Shift 'n-1' disks from 'A' to ‘C'.
Shift last disk from 'A' to ‘B'.
Shift 'n-1' disks from ‘C' to ‘B'.

Step 1 − Move n-1 disks from source to aux


Step 2 − Move n disk from source to dest
th

Step 3 − Move n-1 disks from aux to dest 46


ALGORITHM:

START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP

47
Recursive Solution requires F(n) = 2n −1 moves for n disk

48

You might also like