Stack and Its Applications - pptx-2
Stack and Its Applications - pptx-2
▪ Stack
▪ Practical applications
► Stacks in validating expressions
► Infix to Postfix conversion
Definition:
▪ Conceptually, a stack is a data structure that allows
adding and removing elements in a particular order
▪ Example:
► Which is the first coin to pick up from
the stack of gold coins?
▪ Push Concerns
► What if when the stack is full?
▪ Pop Concerns
► What if the stack is empty
Solution:
▪ Before any push, check if the stack is already filled or not
► If it is filled then generate error message e.g., Stack
Overflow
▪ Before pop, check if stack is not already empty
▪ Real life
► Stack of trays in cafeteria
► Piles of books in library
▪ Computer Science
► Compilers use stacks to evaluate expressions & syntax
parsing
► Program execution stack
► Undo operations
► Expression conversion
► Infix to post-, pre-fix and vice versa
► Tower of Hanoi
► And many more …
▪ LIFO
► Push = Insert at head
▪ Stack
▪ Practical applications
► Stacks in validating expressions
► Infix to Postfix conversion
Validation
▪ There is an equal number of right and left parentheses
▪ Every right parenthesis is preceded by a matching left
parenthesis (A+B) * C Valid
A + B) Invalid
(A+B] Invalid
Lecture 6: Stack & Its 23
Rules
((A+B) (A*B)
122221 11110
I = pop (s);
if ( I is not the matching opener of symb)
valid = false;
}// end of else
} //end while
If (valid)
cout << “Valid String” << endl;
Else
tures & Algorithms
Lecture 6: Stack & Its Applications 27
cout << “not a valid string”
Stacks in validating expression
{ x + (y – [a +b]) }
( ( (
{ { { { {
1 2 3 4 5 6 7
Example:
A+B*C
A+(B*C) Parentheses for emphasis
A+(BC*) Convert the multiplication, Let D=BC*
A+D Convert the addition
AD+
ABC*+ Postfix Form
623+-382/+*2^3+
Final answer is
a) 49
b) 51
c) 52
d) 7
e) None of these