Stack and Its Application
Stack and Its Application
1
Abstract Data Type
2
Examples
Basic Types
integer, real (floating point), boolean (0,1), character
Arrays
A[0..99] : integer array
0 1 2 3 4 5 6 7 99
A …
2 1 3 3 2 9 9 6 10
0 1 2 99
3
ADT: Array
4
Abstract Data Types (ADTs)
An ADT specifies:
Data stored
Operations on the data
Error conditions associated with
operations
5
ADT for stock trade
6
Stack ADT
Objects:
A finite sequence of nodes
Operations:
Create
Push: Insert element at top
Top: Return top element
Pop: Remove and return top element
IsEmpty: test for emptyness
Exceptions
8
DATA
STRUCTURE
10
What is Stack?
A stack is called a last-in-first-out (LIFO) collection.
This means that the last thing we added (pushed) is the
first thing that gets pulled (popped) off.
11
Examples of Stack:
12
Operations
13
Continue…
14
Insertion in Stack: (push)
Insertion(A,TOP,x,max)
Algorithm to push an item “x” into stack A
15
Deletion In Stack: (Pop)
Deletion(A,TOP,x)
Algorithm to pop an element “x” from stack A.
16
Display Operation in Stack:
Display(TOP,i,A[i])
Algorithm to display the elements in stack “A”
17
What is this good for ?
18
Applications of Stacks
1. Reversing Strings:
20
Applications of Stacks
23
Applications of Stacks
INFIX notation:
The general way of writing arithmetic expressions is
known as infix notation. e.g, (a+b)
PREFIX notation:
e.g, +AB
POSTFIX notation:
e.g: AB+
24
Algorithm to Convert INFIX into
POSTFIX
25
Conversion of Infix Into Postfix
Example: Convert Infix expression: (2+(4-1)*3)
into Postfix Expression
CURRENT ACTION STACK POSTFIX
SYMBOL PERFORMED STATUS EXPRESSION
( PUSH ( (
2 2
+ PUSH + (+ 2
( PUSH ( (+( 24
4 24
- PUSH - (+(- 24
1 241
) POP (+ 241-
* PUSH * (+* 241-
3 241-3
) POP * (+ 241-3*
POP + ) 241-3*+ 26
Continue…
EXAMPLE: A+(B*C-(D/E-F)*G)*H
27
28
Step 1 : Scan the Infix Expression from left to right.
Step 2 : If the scanned character is an operand, append it with final Infix to
Postfix string.
Step 3.2 : Else, Pop all the operators from the stack which are greater than
or equal to in precedence than that of the scanned operator. After doing
that Push the scanned operator to the stack. (If you encounter parenthesis
while popping then stop there and push the scanned operator in the stack.)
Step 4 : If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
Step 5 : If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and output it
until a ‘(‘ or ‘[‘ or ‘{‘ respectively is encountered, and discard both the
parenthesis.
30
Algorithm to Evaluate Postfix Expression
31
THANK YOU
32