CSI-402
DATA STRUCTURE AND ALGORITHMS
STACK ADT
STACK
• A structure consisting of homogeneous elements and:
• Insertion and deletions takes place at one end called top
• It is a commonly used abstract data type with two major operations,
namely push and pop.
• Other names
• Last In First Out (LIFO) Structure
• First In Last Out (FILO) Structure
2
R E AL L I FE SCE NAR I OS
• Books on floor
• Dishes on a shelf
• In programming, consider doing X = (A+B) * (C+D)
3
STACK ADT OP E R ATI ONS
• Stack ADT emphasizes specific operations
• Uses an explicit linear ordering (Random access is intentionally revoked)
• Insertions and removals are performed individually.
• Inserted objects are pushed onto the stack
• Top of stack is most recent object pushed onto stack
• Push and pop operations changes current top value of stack
4
STACK ADT OPE R AT I ONS
• Graphically, the stack operations are viewed as follows:
5
STACK ADT OP E R ATI ONS
• CreateStack(S)
• Make Stack S be an empty stack
• Top(S)
• Return the element at the top of stack S
• Pop(S)
• Remove the top element of the stack
• Push(S,x)
• Insert the element x at the top of the stack
• Empty(S)
• Return true if S is an empty stack and return false otherwise
6
PUSH AND P OP OP E R ATI ONS OF STACK
7
AP P L I C ATI ONS
• Parsing code
• Matching parenthesis problem
• Tracking function calls (Call stack)
• Reversing a string
• Infix to postfix Conversion
• Backtracking in Depth-First-Search
8
USE OF STACK I N FUNCT I ON C AL L S
• When a function begins execution, an activation record is created
to store current execution environment for that function
• Activation records all necessary information about a function call
• arguments passed by the caller function
• Local variables
• Content of the registers
• Return address to the caller function
• Address of instruction following the function call
9
USE OF STACK I N FUNCT I ON C AL L S
• Each invocation of a function has its own activation record
• Recursive/Multiple calls to the functions require several
activation records to exist simultaneously
• A function returns only after all functions it calls have returned
Last In First Out (LIFO) behavior
• A program/OS keeps track of all the functions that have been
called using run-time stack or call stack
10
RU NT I ME STACK E XAMPL E
void main(){
int a=3;
f1(a); // statement A
cout << endl;
}
void f1(int x){
cout << f2(x+1); // statement B
}
int f2(int p){
int q=f3(p/2); // statement C
return 2*q;
}
int f3(int n){
return n*n+1;
}
11
RUNT I ME STACK
• When a function is called
• Copy of activation record pushed onto run-time stack
• Arguments copied into parameter spaces
• Control is transferred to starting address of body of function
Function
Return value Local
Parameters value variables Return address
OS denotes that when execution of main() is completed, it returns
to operating system
12
STACK L I BR ARY ( C+ +)
13
STACK L I B R ARY ( J AVA)
14
STATI C AND DY NAMI C STACK S
There are two kinds of stack data structure:
• static, they have a fixed size and implemented as arrays.
• dynamic, they grow in size as needed and implemented as
linked lists
15
AR R AY I MPL E MENTAT ION – FI R ST SOL UT I ON
• Elements are stored in contiguous cells of an array
• New elements can be inserted to the top of the list
top last-pushed Element
Second-last Element
List
1st pushed Element
Empty
maxlength
16
AR R AY I MPL E MENTAT ION – FI R ST SOL UT I ON
Problem
• Every PUSH and POP requires moving entire array up and down
• Fixed size
231
2
1
1
…
17
AR R AY I MPL E MENTAT ION – T W E AK E D SOL UT I ON
1 1st pushed Element
2 2nd -pushed Element List
…
top Last-pushed Element
Empty
maxlength
Idea
• Anchor the bottom of stack at the start of array
• Let the stack grow towards end of array
• Top indicates current position of recently inserted stack element
18
USI NG STACK ( C+ +)
19
USI NG STACK ( J AVA)
20
T H E TOW E R S OF H ANOI
A STACK - B ASE D AP P L I C ATI ON
• GIVEN: three poles
• a set of discs on first pole, discs of different sizes, smallest discs
at top
• GOAL: move all discs from left pole to right one.
• CONDITIONS: only one disc may be moved at a time.
• A disc can be placed either on an empty pole or on top of a
larger disc.
23
TOW E R S OF H ANOI
24
TOWE R S OF H ANOI
25
TOWE R S OF H ANOI
26
TOWE R S OF H ANOI
27
TOWE R S OF H ANOI
28
TOWE R S OF H ANOI
29
TOWE R S OF H ANOI
30
TOWE R S OF H ANOI
31
AL G E BR AIC E XP R E SSIONS
• An algebraic expression is combination of operands and operators
• Operand is a quantity that is operated on
• Operator is a symbol that signifies a mathematical or logical operation
32
ASSOCI ATI V I T Y OF OP E R ATOR S
() Parentheses (function call)
[] Brackets (array subscript)
. Member selection via object name left-to-right
-> Member selection via pointer
++ – – Postfix increment/decrement
++ – – Prefix increment/decrement
+– Unary plus/minus right-to-left
!~ Logical negation/bitwise complement
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment 33
I NFI X, POST FI X AND P R E FI X E XP R E SSI ONS
• Infix
• Expressions in which operands surround the operators
• Example: A+B-C
• Postfix or Reverse Polish Notation (RPN)
• Operators comes after the operands
• Example: AB+C-
• Prefix or Polish Notation
• Operator comes before the operands
• Example: -+ABC
34
E XAMPL E: CONV E R SI ON FROM I NFI X TO POST FI X
• Infix: A+B*C
• Conversion: Applying the rules of precedence
A+(B*C) Parentheses for emphasis
A+(BC*) Convert the multiplication
ABC*+ Postfix Form
35
E XAMPL E: CONV E R SI ON FROM I NFI X TO POST FI X
• Infix: ( (A+B)*C-(D-E) ) $ (F+G)
• Conversion: Applying the rules of precedence
( (AB+)*C-(DE-) ) $ (FG+)
( (AB+C*)-(DE-) ) $ (FG+)
(AB+C*DE--) $ (FG+)
AB+C*DE- -FG+$
• Exercise: Convert the following to Postfix
( A + B ) * ( C – D)
A / B * C – D + E / F / (G + H)
36
I NF I X , POST FI X AND P R E FI X E X P R E SSI ONS E X A MP L ES
Infix PostFix Prefix
A+B AB+ +AB
(A+B) * (C + D) AB+CD+* *+AB+CD
A-B/(C*D^E) ? ?
37
W H Y DO W E NE E D P R E FI X AND P OST FI X ?
• Normally, algebraic expressions are written using infix notation
• For example: (3 + 4) × 5 – 6
• Appearance may be misleading; infix notations are not as simple as
they seem
• Operator precedence
• Associativity property
• Operators have precedence: Parentheses are often required
▪ (3 + 4) × 5 – 6 = 29
▪ 3+4 × 5–6 = 17
▪ (3 + 4) × (5 – 6) = –7
▪ 3 + 4 × (5 – 6) = –1
38
W H Y DO W E NE E D P R E FI X AND P OST FI X ?
• Infix Expression is Hard To Parse and difficult to evaluate
• Postfix and prefix do not rely on operator priority and are easier to
parse
• No ambiguity and no brackets are required
• Many compilers first translate algebraic expressions into some form
of postfix notation
• Afterwards translate this postfix expression into machine code
39
E XPR E SSION E VAL UATI ON ( MAJ OR CH AL L ENGES)
• We face two problems to evaluate an expression
1. Given an infix expression, convert it into a postfix expressions.
2. Evaluation of postfix expression and calculate the solution
Let’s address the second problem first
40
E XAMPL E: POST FI X E XP R E SSIONS E VAL UATION
41
E X AMP L E: P OST F I X E X P R E SSIONS E VA L UAT ION
A ND U SE OF STAC K
42
E XAMPL E: POST FI X E XPR E SSIONS E VAL UAT ION
AND USE OF STACK
What does the following postfix expression evaluate to?
632+*
A. 18
B. 36
C. 24
D. 11
E. 30
43
E VAL UATING A P OST FI X E XP R E SSI ON
Each operator in postfix string refers to previous two operands in string.
44
E VAL UAT ING A POST FI X E XPR E SSI ON
Example Postfix Expression:
623+-382/+*2$3+ symb opnd1 opnd2 result stack
45
E VAL UATING A P OST FI X E XP R E SSI ON
Example Postfix Expression:
623+-382/+*2$3+ symb opnd1 opnd2 result stack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
$ 7 2 49 49
3 7 2 49 49,3
+ 49 3 52 52
46
I NFI X TO POST FI X ( W I T H OUT PAR E NT H E SIS)
• Token is an operand
• Append it to the end of postfix string
• Token is an operator, *, /, +, or –
• First remove any operators already on the opstk OR stack that have higher
or equal precedence and append them to the postfix string
• Push the token on the opstk OR stack
• Input expression has been completely processed
• Any operators still on opstk OR stack should be removed and appended to
the end of the postfix string
• Example: 4 - 2 + 6 * 2
47
CONV E R SI ON OF I NFI X TO POST FI X
• Precedence function
• prcd(op1, op2)
• op1 and op2 are characters representing operators
• Precedence function returns TRUE
• If op1 has precedence over op2 (OR) op1 is same as op2
• Otherwise function returns FALSE
• Examples
• prcd(‘*’ , ’+’) returns TRUE
• prcd(‘+’ , ’+’) returns TRUE
• prcd(‘+’ , ’*’) returns FALSE
48
AL G OR I T HM TO CONV E RT I NFI X TO POST FI X
Example: A+B*C
symb Postfix string opstk
A A
49
AL G OR I T HM TO C ONV E RT I NFI X TO P OST FI X
Example: A+B*C
symb Postfix string opstk
A A
+ A +
50
AL G OR I T HM TO C ONV E RT I NFI X TO P OST FI X
Example: A+B*C
symb Postfix string opstk
A A
+ A +
B AB +
51
AL G OR I T HM TO C ONV E RT I NFI X TO P OST FI X
Example: A+B*C
symb Postfix string opstk
A A
+ A +
B AB +
* AB +*
C ABC +*
ABC* +
ABC*+ 52
I NFI X TO POST FI X ( PR ACT I CE)
Example: A*B+C
symb Postfix string opstk
53
I NFI X TO POST FI X CONV E R SION ( P R ACT I CE )
Example: A*B+C
symb Postfix string opstk
A A
* A *
B AB *
+ AB* +
C AB*C +
AB*C+ 54
I NFI X TO POST FI X ( WI T H PAR E NT H E SIS)
• Token is an operand
• Append it to the end of postfix string
• Token is a left parenthesis
• Push it on the opstk
• Token is a right parenthesis
• Pop the opstk until corresponding left parenthesis is removed
• Append each operator to end of postfix string
• Pop the left parenthesis from stack [opstk] and discard it as well
• Token is an operator, *, /, +, or –
• Push it on the opstk
• First remove any operators already on opstk that have higher or
equal precedence and append them to postfix string
• Input expression has been completely processed
• Any operators still on opstk can be removed and appended to end
of postfix string 55
W H AT I F E XPR E SSION CONTAI NS PAR E NT H E SI S ?
R E QUI R ED AL G OR I TH MIC CH ANG ES
• Precedence function prcd(op1, op2) has to be modified
• prcd( ‘(‘ , op) = FALSE For any operator op
• prcd( op , ‘(‘ ) = FALSE For any operator op other than ‘)’
• In short, whenever a ‘(’ is encountered → Push it onto stack
• FALSE will ensure that by terminating the while-loop
• prcd( op , ‘)‘ ) = TRUE For any operator op other than ‘(‘
• We can pop all the operators until a starting parathesis is not
encountered from the stack
• prcd( ‘)‘ , op ) = undef For any operator op (an error)
• As you will never push closing parenthesis in the stack, so, this case will
never be encountered
56
AL G OR I T HM TO C ONV E RT I NFI X TO P OST FI X
Example: (A+B)*C
symb Postfix string opstk
57
AL G OR I T HM TO C ONV E RT I NFI X TO P OST FI X
Example: (A+B)*C
symb Postfix string opstk
( (
A A (
+ A (+
B AB (+
) AB+
* AB+ *
C AB+C *
AB+C* 58
I NFI X TO POST FI X CONV E R SION ( P R ACT I CE )
Example: ( (A-(B+C) ) *D ) $ (E+F) symb Postfix string opstk
59
I NFI X TO POST FI X CONV E R SION ( P R ACT I CE )
Example: ( (A-(B+C) ) *D ) $ (E+F) symb Postfix string opstk
( (
( ((
A A ((
- A ((-
( A ((-(
B AB ((-(
+ AB ((-(+
C ABC ((-(+
) ABC+ ((-
) ABC+- (
* ABC+- (*
D ABC+-D (*
) ABC+-D*
$ ABC+-D* $
( ABC+-D* $(
E ABC+-D*E $(
+ ABC+-D*E $(+
F ABC+-D*EF $(+
) ABC+-D*EF+ $
60 ABC+-D*EF+$
CONV E R SI ON TO P R E FI X E XP R E SSION
• An Infix to Prefix Conversion Algorithm
• Reverse the infix string
• Adjust parenthesis, i.e., make every '(' as ')' and every ')' as '('
• Perform infix to postfix algorithm on reversed string
• Reverse output postfix expression to get prefix expression
• Example: (A + B) * (B – C)
• )C – B( * )B + A( → (C – B) * (B + A) Reverse infix string
• C B - B A + * Perform infix to postfix conversion
• * + A B - B C Reverse postfix to get prefix expression
61
CONV E R SI ON TO P R E FI X E XP R E SSION
• Example: (A+B^C)*D+E^5
• 5^E+D*)C^B+A( → 5^E+D*(C^B+A) Reverse infix string
• 5E^DCB^A+*+ Perform infix to postfix conversion
• +*+A^BCD^E5 Reverse postfix to get prefix expression
62
END