You are on page 1of 35

Unit 3: Linear Data Structures: Stack

UNIT 3

LINEAR DATA STRUCTURES: STACK


4 HOURS

DR. NEEPA SHAH 1

SYLLABUS CONTENT

 Stack as an ADT
 Operations
 Array and Linked List representation of Stack
 Applications
 Reversing data
 Conversion of Infix to prefix and postfix expression
 Evaluation of postfix and prefix expressions
 Balanced parenthesis, etc.

DR. NEEPA SHAH 2

Dr. Neepa Shah 1


Unit 3: Linear Data Structures: Stack

STACK

 A stack is a linear data structure in which all additions and deletions are restricted to one end, called the top. Stacks
are known as the last in–first out (LIFO) data structure.
 Imagine these objects are in a glass jar

DR. NEEPA SHAH 3

THE STACK ADT

 Main stack operations:


 push (elemType newElem): inserts an element newElem
 elemType pop ( ): removes and returns the last inserted element

 Auxiliary stack operations:


 elemType peek ( ): returns the last inserted element without removing it
 int size ( ): returns the number of elements stored
 int isEmpty ( ): indicates whether no elements are stored

Simulation: https://yongdanielliang.github.io/animation/web/Stack.html
DR. NEEPA SHAH 4

Dr. Neepa Shah 2


Unit 3: Linear Data Structures: Stack

ARRAY-BASED STACK

 A simple way of implementing the Stack ADT uses an array


 We add elements from left to right
 A variable keeps track of the index of the top element
 The array storing the stack elements may become full
 A push operation will then generate error
 Limitation of the array-based implementation


S
0 1 2 t
DR. NEEPA SHAH 5

PUSH FUNCTION: ALGORITHM

 Step 1: Start
 Step 2: Check if the stack is full or not (top = MAX-1)
If the stack is full,Then print "Stack Overflow“
 Step 3: Else, // the stack is not full
Increment top by 1 and Set, a[top] = newElem
 Step 4: Stop

DR. NEEPA SHAH 6

Dr. Neepa Shah 3


Unit 3: Linear Data Structures: Stack

POP FUNCTION: ALGORITHM

 Step 1: Start

 Step 2: Check if the stack is empty


If top is less than 0, then stack is empty, print "Stack Underflow"

 Step 3: Else, store the value pointed by top in a variable elem=a[top] and decrement top by 1.

DR. NEEPA SHAH 7

PEEK FUNCTION: ALGORITHM

 Step 1: Start

 Step 2: Check if the stack is empty


If top is less than 0, then stack is empty, print "Stack Underflow"

 Step 3: Else, store the value pointed by top in a variable elem=a[top].

DR. NEEPA SHAH 8

Dr. Neepa Shah 4


Unit 3: Linear Data Structures: Stack

SIZE ( ) AND ISEMPTY ( )

 size ( )
 return (top+1)

 isEmpty ( )
 Step 1: Start
 Step 2: if the stack is empty then return 1
 Step 3: Else, return 0

DR. NEEPA SHAH 9

PERFORMANCE AND LIMITATIONS

 Performance
 Let n be the number of elements in the stack
 The space used is O(n)
 Each operation runs in time O(1)

 Limitations
 The maximum size of the stack must be defined a priori and cannot be changed
 Trying to push a new element into a full stack causes an implementation-specific error

DR. NEEPA SHAH 10

Dr. Neepa Shah 5


Unit 3: Linear Data Structures: Stack

APPLICATIONS OF STACK

 Reversing an array or list


 Parenthesis Matching
 HTML tag Matching
 Recursion / Function Invocation
 Decimal to binary conversion
 Conversion of Arithmetic Expressions
 Evaluation of Arithmetic Expression
 Traversal Algorithm

DR. NEEPA SHAH 11

PARENTHESES MATCHING

 Each “(”,“{”, or “[” must be paired with a matching “)”,“}”, or “[”


 correct: ( ) (( )) {([( )])}
 correct: ((( )(( )) {([( )])}
 incorrect: )(( )) {([( )])}
 incorrect: ({[ ])}
 incorrect: (

DR. NEEPA SHAH 12

Dr. Neepa Shah 6


Unit 3: Linear Data Structures: Stack

PARENTHESES MATCHING ALGORITHM

Algorithm ParenMatch(X,n):
Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number
Output: true if and only if all the grouping symbols in X match
Let S be an empty stack
for i=0 to n-1 do
if X[i] is an opening grouping symbol then
S.push(X[i])
else if X[i] is a closing grouping symbol then
if S.isEmpty() then
return false {nothing to match with}
if S.pop() does not match the type of X[i] then
return false {wrong type}
if S.isEmpty() then
return true {every symbol matched}
else
return false {some symbols were never matched}

DR. NEEPA SHAH 13

FUNCTION INVOCATION

Dr. Neepa Shah 14


DR. NEEPA SHAH 14

Dr. Neepa Shah 7


Unit 3: Linear Data Structures: Stack

FUNCTION INVOCATION CONTD.

 Program Stack
 Program Counter
 Stack Frame

 Stack Frame is pushed into stack.


 Sub-routine instructions are executed.
 Stack Frame is popped from the stack.
 Now Program Counter is holding the return address.

Dr. Neepa Shah 15


DR. NEEPA SHAH 15

METHOD STACK
main() {
 To keep track of the chain of active methods with int i = 5;
a stack foo(i); bar
} PC = 1
 When a method is called, push a frame containing m=6
on the stack foo(int j) {
int k;
 Local variables and return value
k = j+1; foo
 Program counter, keeping track of the statement bar(k); PC = 3
being executed } j=5
 When a method ends, its frame is popped from bar(int m) { k=6
the stack and control is passed to the method on …
top of the stack }
main
PC = 2
Dr. Neepa Shah
i=5
DR. NEEPA SHAH 16

Dr. Neepa Shah 8


Unit 3: Linear Data Structures: Stack

RECURSION INVOCATION

DR. NEEPA SHAH 17

RECURSION CONTD.

int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}

DR. NEEPA SHAH 18

Dr. Neepa Shah 9


Unit 3: Linear Data Structures: Stack

RECURSION CONTD.

DR. NEEPA SHAH 19

RECURSION CONTD.

 factorial(5) returns 5 * factorial(4)


 factorial(4) returns 4 * factorial(3)  factorial(5) returns 5 * factorial(4) = 5 * 24 = 120
 factorial(3) returns 3 * factorial(2)
 factorial(4) returns 4 * factorial(3) = 4 * 6 = 24
 factorial(2) returns 2 * factorial(1)
 factorial(3) returns 3 * factorial(2) = 2 so 3 * 2 = 6
 factorial(1) returns 1 * factorial(0)
 factorial(2) returns 2 * factorial(1) = 1 so 2 * 1 = 2
 factorial(0) returns 1
 factorial(1) returns 1 * factorial(0) = 1 so 1 * 1 = 1
 factorial(0) returns 1

DR. NEEPA SHAH 20

Dr. Neepa Shah 10


Unit 3: Linear Data Structures: Stack

INFIX, PREFIX, POSTFIX EXPRESSIONS

 We usually write algebraic expressions like this:


a+b
 This is called infix notation, because the operator (“+”) is inside the expression

 A problem is that we need parentheses or precedence rules to handle more complicated expressions:
For Example :
a + b * c = (a + b) * c ?
= a + (b * c) ?

DR. NEEPA SHAH 21

INFIX, POSTFIX, & PREFIX NOTATION

 Infix form : <identifier> <operator> <identifier>


 Postfix form : <identifier> <identifier> <operator>
 Prefix form : <operator> <identifier> <identifier>

 Infix notation: a + b
 Prefix notation: + a b
 Postfix notation: a b +

DR. NEEPA SHAH 22

Dr. Neepa Shah 11


Unit 3: Linear Data Structures: Stack

INFIX, POSTFIX, & PREFIX NOTATION CONTD.

 Other Names
 Prefix notation:“Polish notation”
 Postfix notation:“Reverse Polish notation” or RPN.
 Why
 With postfix and prefix notations, parentheses are no longer needed!

DR. NEEPA SHAH 23

POSTFIX EXPRESSION

 Expressions normally written in infix form


 Binary operators appear between their operands:
 a+b c*d e*f-g

 A computer normally scans in input order


 One must always compute operand values first
 So easier to evaluate in postfix form:
 ab+ cd* ef*g-

DR. NEEPA SHAH 24

Dr. Neepa Shah 12


Unit 3: Linear Data Structures: Stack

POSTFIX EXPRESSION: ADVANTAGES

 No need to use parentheses for grouping


 No need to use precedence rules:
 Usual meaning of a + b * c is a + (b * c)
 * takes precedence over +
 Postfix: a b c * +
 For (a + b) * c, postfix is: a b + c *

DR. NEEPA SHAH 25

EXAMPLE

infix postfix prefix

(a + b) * c ab+c* *+abc
a + (b * c) abc*+ +a*bc

DR. NEEPA SHAH 26

Dr. Neepa Shah 13


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION


stackVect
infixVect
(a+b-c)*d–(e+f)

postfixVect

DR. NEEPA SHAH 27

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
a+b-c)*d–(e+f)

postfixVect

(
DR. NEEPA SHAH 28

Dr. Neepa Shah 14


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
+b-c)*d–(e+f)

postfixVect
a
(
DR. NEEPA SHAH 29

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
b-c)*d–(e+f)

postfixVect
+ a
(

DR. NEEPA SHAH 30

Dr. Neepa Shah 15


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
*c)*d–(e+f)

postfixVect
ab
+
(
DR. NEEPA SHAH 31

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
c)*d–(e+f)

postfixVect
- ab+
(
DR. NEEPA SHAH 32

Dr. Neepa Shah 16


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
)*d–(e+f)

postfixVect
- ab+c
(
DR. NEEPA SHAH 33

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
*d–(e+f)

postfixVect
ab+c-

DR. NEEPA SHAH 34

Dr. Neepa Shah 17


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
d–(e+f)

postfixVect
ab+c-

*
DR. NEEPA SHAH 35

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
–(e+f)

postfixVect
ab+c-d
*

DR. NEEPA SHAH 36

Dr. Neepa Shah 18


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
(e+f)

postfixVect
ab+c–d*
-

DR. NEEPA SHAH 37

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
e+f)

postfixVect
(
ab+c–d*
-

DR. NEEPA SHAH 38

Dr. Neepa Shah 19


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
+f)

postfixVect
( ab+c–d*e
-
DR. NEEPA SHAH 39

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
f)

postfixVect
+
( ab+c–d*e
-
DR. NEEPA SHAH 40

Dr. Neepa Shah 20


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect
)

+ postfixVect
( ab+c–d*ef
-

DR. NEEPA SHAH 41

INFIX TO POSTFIX CONVERSION CONTD.

infixVect

postfixVect
ab+c–d*ef+
-
DR. NEEPA SHAH 42

Dr. Neepa Shah 21


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION CONTD.

infixVect

postfixVect
ab+c–d*ef+-

DR. NEEPA SHAH 43

Expression Stack Output


2 Empty 2
* * 2
CONVERT 2*3/(2-1)+5*3 3 * 23
INTO POSTFIX FORM
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
* +* 23*21-/53
3 +* 23*21-/53
DR. NEEPA SHAH 44
Empty 23*21-/53*+
35

Dr. Neepa Shah 22


Unit 3: Linear Data Structures: Stack

ALGORITHM FOR INFIX TO POSTFIX


1. Examine the next element in the input (from left to right).
2. If it is operand, output it.
3. If it is opening parenthesis, push it on stack.
4. If it is a closing parenthesis, pop operators from stack and output them until an opening parenthesis is encountered. pop and
discard the opening parenthesis.
5. If it is an operator, then
i. If stack is empty, push operator on stack.
ii. If the top of stack is opening parenthesis, push operator on stack
iii. If it has higher priority than the top of stack, push operator on stack.
iv. If it has lower precedence then pop all the operators from the stack which are greater than the precedence of incoming
operator and now, push the operator on the stack.
v. If the incoming operator has the same precedence with the top of the stack then use the associativity rules. If the
associativity is from left to right (*, /, %, + and -) then pop and print the top of the stack then push the incoming operator.
If the associativity is from right to left (^) then push the incoming operator.
6. go to step 1
45
7. If there is no more input, pop the remaining operators to output one by one till the stack is not empty.
DR. NEEPA SHAH

Infix to Postfix with exponent (associativity is R to L)

step1: step2:

step3: step4:

DR. NEEPA SHAH 46

Dr. Neepa Shah 23


Unit 3: Linear Data Structures: Stack

Infix to Postfix with exponent (associativity is R to L)


step5: step6:

step7: step8:

DR. NEEPA SHAH 47

Infix to Postfix with exponent (associativity is R to L)


step9: step10:

step11: step12:

DR. NEEPA SHAH 48

Dr. Neepa Shah 24


Unit 3: Linear Data Structures: Stack

Infix to Postfix with exponent (associativity is R to L)


step13: step14:

step15: step16:

DR. NEEPA SHAH 49

Infix to Postfix with exponent (associativity is R to L)


step17: step18:

DR. NEEPA SHAH 50

Dr. Neepa Shah 25


Unit 3: Linear Data Structures: Stack

INFIX TO POSTFIX CONVERSION (INTUITIVE ALGORITHM)

(1) Fully parenthesized expression


a / b - c + d * e - a * c -->
((((a / b) - c) + (d * e)) – (a * c))

(2) All operators replace their corresponding right


parentheses.
((((a / b) - c) + (d * e)) – (a * c))

/ - +* -*
(3) Delete all parentheses.
ab/c-de*+ac*-

Dr. Neepa Shah 51


DR. NEEPA SHAH

PRACTICE EXAMPLES

Infix Postfix
2+3*4 234*+
a*b+5 ab*5+
(1+2)*7 12+7*
a*b/c ab*c/
(a/(b-c+d))*(e-a)*c abc-d+/ea-*c*
a/b-c+d*e-a*c ab/c-de*+ac*-
DR. NEEPA SHAH 52

Dr. Neepa Shah 26


Unit 3: Linear Data Structures: Stack

PRACTICE EXAMPLES CONTD.

 x
 x+y
 (x + y) - z
 w * ((x + y) - z)
 (2 * a) / ((a + b) * (a - c))

DR. NEEPA SHAH 53

ALGORITHM FOR INFIX TO PREFIX

1. First, reverse the given infix expression and scan the expression from left to right.
2. If it is operand, output it.
3. If it is ')', then push it into the stack.
4. If it is '(', pop operators from stack and output them until an opening parenthesis is encountered. Pop and discard the opening parenthesis.
5. If it is an operator
i. If the stack is empty, then push the operator on stack.
ii. If the top of the stack is ')', push the operator on the stack.
iii. If it has higher precedence than the TOP of the stack, push it (the incoming operator) into the stack.
iv. If it has the same precedence with a TOP of the stack, push it into the stack.
v. If it has lower precedence then pop the operator from the stack till it finds the operator of a lower precedence or same precedence
vi. If has the same precedence with the top of the stack and it is ‘^’, then pop the top of the stack till the condition is true. If the condition is not
true, push the ^ operator.
6. When we reach the end of the expression, pop, and print all the operators from the top of the stack.
7. At the end, reverse the output.

DR. NEEPA SHAH 55

Dr. Neepa Shah 27


Unit 3: Linear Data Structures: Stack

Input Token Stack Expression


F F

EXAMPLE: INFIX TO PREFIX ^ ^ F


) ^) FE
E ^) FE
– ^)- FE
D ^)- FED

 (A+B)+C-(D-E)^F ( ^)- FED-

 After Reversing: F^)E-D(-C+)B+A( – – FED-^

 Reverse final output C – FED-^C

 Prefix: - + + A B C ^ - D E F + –+ FED-^C
) –+) FED-^C
B –+) FED-^CB
+ –+)+ FED-^CB
A –+)+ FED-^CBA
DR. NEEPA SHAH 56
( –+ FED-^CBA+
FED-^CBA++–

INFIX TO PREFIX

 Example: K + L - M * N + (O^P) * W/U/V * T + Q


 Reverse the expression: Q + T * V/U/W * ) P^O(+ N*M - L + K

DR. NEEPA SHAH 57

Dr. Neepa Shah 28


Unit 3: Linear Data Structures: Stack

INFIX TO PREFIX CONVERSION (INTUITIVE ALGORITHM) CONTD.

DR. NEEPA SHAH 58

INFIX TO PREFIX CONVERSION (INTUITIVE ALGORITHM) CONTD.

DR. NEEPA SHAH 59

Dr. Neepa Shah 29


Unit 3: Linear Data Structures: Stack

PRACTICE INFIX-POSTFIX AND PREFIX CONVERSION

1. A+B*C+D
2. A+B+C+D
3. (A + B) * (C + D)
4. (A+B)*(C/D)
5. A * B- (C + D) + E
6. A*(B*C+D*E)+F
7. (A+B)*C+(D-E)/F+G
8. K + L - M*N + (O^P) * W/U/V * T + Q
9. (2-3+4)*(5+6*7)
10. 2-3+4-5*6

DR. NEEPA SHAH 60

POSTFIX EVALUATION EXAMPLES

Postfix Evaluation
234*-5+ -5
23-45+* -9
234*5+- -15

DR. NEEPA SHAH 61

Dr. Neepa Shah 30


Unit 3: Linear Data Structures: Stack

EVALUATION A POSTFIX EXPRESSION

 Each operator in a postfix string refers to the previous two operands in the string.
 Suppose that each time we read an operand we push it into a stack. When we reach an operator, its
operands will then be top two elements on the stack
 We can then pop these two elements, perform the indicated operation on them, and push the result
on the stack.
 So that it will be available for use as an operand of the next operator.

DR. NEEPA SHAH 62

EXAMPLE: POSTFIX EXPRESSIONS

DR. NEEPA SHAH 63

Dr. Neepa Shah 31


Unit 3: Linear Data Structures: Stack

POSTFIX EXPRESSIONS: ALGORITHM USING STACKS

DR. NEEPA SHAH 64

ALGORITHM FOR EVALUATING A POSTFIX EXPRESSION

WHILE more input items exist


{
If symb is an operand
then push (opndstk, symb)
else //symbol is an operator
{
Opnd2=pop(opndstk);
Opnd1=pop(opndstk);
Value = result of applying symb to opnd1 & opnd2
Push(opndstk,value);
} //End of else
} // end while
Result = pop (opndstk);

DR. NEEPA SHAH 65

Dr. Neepa Shah 32


Unit 3: Linear Data Structures: Stack

EVALUATE THE POSTFIX EXPRESSION: 623+-382/+*2^3+

Final answer is
• 49
• 51
• 52
• 7
• None of these

DR. NEEPA SHAH 66

EVALUATE: 623+-382/+*2^3+
Symbol Opnd1 Opnd2 Value OpendStk
6 6
2 6, 2
3 6, 2, 3
+ 2 3 5 6, 5
- 6 5 1 1
3 1, 3
8 1, 3, 8
2 1, 3, 8, 2
/ 8 2 4 1, 3, 4
+ 3 4 7 1, 7
* 1 7 7 7
2 7, 2
DR. NEEPA SHAH
^ 7 2 49 49 67
3 49, 3
+ 49 3 52 52

Dr. Neepa Shah 33


Unit 3: Linear Data Structures: Stack

PRACTICE: POSTFIX EVALUATION

1. 2 3 4 * +
2. 3 4 * 2 5 * +
3. 6 3 2 4 + – *
4. 10 5 60 6 / * 8 –
5. 5 4 6 + * 4 9 3 / + *
6. 23-4+56*-
7. 23-4+567*+*

DR. NEEPA SHAH 68

EVALUATION A PREFIX EXPRESSION

 Step 1: Start Evaluating expression from right to left or reverse the expression
 Step 2: If a character is an operand push it to Stack
 Step 3: If the character is an operator
 pop two elements from the Stack.
 Operate on these elements according to the operator, and push the result back to the Stack
 Step 4: Step 2 and 3 will be repeated until the end has reached.
 Step 5:The Result is stored at the top of the Stack, return it

DR. NEEPA SHAH 69

Dr. Neepa Shah 34


Unit 3: Linear Data Structures: Stack

PRACTICE EXAMPLES

 +9*26
 *+69-31
 - * + 2 2 3 10
 -+8/632
 -+7*45+20
 /+33-+47*+123
 -/*2*5+3652

DR. NEEPA SHAH 70

Dr. Neepa Shah 35

You might also like