SlideShare une entreprise Scribd logo
1  sur  83
Data Structure
Stack
2
Stack data structure
Stack data structure is like a container with a single opening.
• Can only access element at the top
• Add/insert new items at the top
• Remove/delete an item from the top
Stack in real life:
• collection of elements arranged in a linear order.
- stack of books, stack of plates, stack of chairs.
3
A stack is open at one end
(the top) only. You can push
entry onto the top, or pop
the top entry out of the stack.
Note that you cannot
add/extract entry in the
middle of the stack.
Stack
A
B
C
bottom
top
push
pop
4
Last-in First-out (LIFO)
A A
B
A
B
C
When we insert entries
onto the stack and then
remove them out one by
one, we will get the entries
in reverse order.
The last one
inserted in is the
first one removed
out! (LIFO)
A A
B
Insert(A);
Insert(B);
Insert(C);
Remove();
Remove();
Remove();
A B C
C
C
B
A
Stack
• A stack or LIFO (last in, first out) is an abstract data type that serves as a
collection of elements, with two principal operations:
• Push: adds an element to the collection;
• Pop: removes the last (top of the stack) element that was added.
• Bounded capacity
• If the stack is full and does not contain enough space to accept an
entity to be pushed, the stack is then considered to be in an overflow
state.
• A pop either reveals previously concealed items or results in an empty
stack – which means no items are present in stack to be removed.
• Non-Bounded capacity
• Dynamically allocate memory for stack. No overflow.
Abstract Data Type (ADT)
• An abstract data type is a type with associated operations, but whose representation is
hidden.
• The basic idea is that the implementation of these operations is written once in the program,
and any other part of the program that needs to perform an operation on the ADT can do so
by calling the appropriate function.
• If for some reason implementation details need to change, it should be easy to do so by
merely changing the routines that perform the ADT operations. This change, in a perfect
world, would be completely transparent to the rest of the program.
Abstract Data Type (ADT)
• A data type whose properties (domain and operations) are
specified independently of any particular implementation.
• ADT is a mathematical model which gives a set of utilities
available to the user but never states the details of its
implementation.
• In OO-Programming a Class is an ADT.
• Let us consider Gmail.
We can do lot of operation with Gmail such as Create Account, Sign in,
Compose, Send, etc.,
We know the required details to Create an
account.
• But we don't know how these operations are functioning in background.
• We don't know how Google team handling these operation to give you the required
output.
• Implementation of operation is always hidden to the user.
• Let us assume Gmail as abstract data type. We can say Gmail is an object with operations
such as create account, sign in, compose, send, etc.,
•Abstract Data Type:
Dr. Kazi A. Kalpoma
16
Stack Operations
• Push(X) – insert element X at the top of the
stack and increment the top index.
• Pop() – remove the element from the top of
the stack with/without returning element and
decrement the top index.
• Top() – return the top element without
removing it from the stack. top index does not
change.
#define stack_size 6;
int top;
char stack[stack_size];
stack implementation by an array
top = 2
stack
stack
?
?
?
?
?
?
0
1
2
3
4
5 (stacksize-1)
Initialization of top index of Stack
stack_initialize()
{
top = -1;
}
?
?
?
?
?
?
top = 0
E--1ntry
top
0
1
2
3
4
5 (stacksize-1)
19
Push(X)
void push(char X)
{
if(top >= stack_size-1)
cout<<“Overflow: stack is full”;
else
{
top++; /increase top by 1
stack[top] = X; /insert the item on top
}
}
X
?
?
?
?
?
top= 0 1
entry
top
top++;
stack[top] = X;
Stack[++top] = X;
0
1
2
3
4
5 (stacksize-1)
Before insertion it needs
first to check the
overflow situation i.e.
stack is full or not full
Pop()
void pop() //pop function is not returning
{
if(top<0)
cout<<"underflow: stack is empty”;
else
{
char X = stack[top];
top--;
}
}
top= 10
entry
top
?
?
?
?
?
?
0
1
2
3
4
5
E--1ntry
Before deletion it needs
first to check the
underflow situation i.e.
stack is empty or not
empty
char X = stack[top];
top--;
char X = stack[top--];
Pop() //pop function is returning the top element
char pop()
{
if(top<0)
cout<<"underflow: stack is empty”;
else
{
char X = stack[top];
top--;
return X;
}
} top= 10
entry
top
?
?
?
?
?
?
0
1
2
3
4
5
E--1ntry
Top()
char Top() //top function is returning top value
{
return stack[top]; //but not reduce top index
} top= 10
entry
top
K
R
?
?
?
?
0
1
2
3
4
5
23
Other operations
int IsEmpty()
{
return ( top < 0 );
}
int IsFull()
{
return ( top >= stack_size-1);
} top = 2
stack
?
?
?
?
?
?
0
1
2
3
4
5 (stacksize-1)
// ……Program for stack implementation
#include <iostream>
using namespace std;
// here add all the initializations and
//functions’ definitions of stack.
int main()
{
push(9);
push(7);
push (8);
push (4);
pop ( );
push (5);
pop ( );
pop ( );
cout<< " top element of stack is = " << top() << endl;
cout << " top index is = " << top << endl;
}
top = 2
stack
9
7
8
4
?
?
0
1
2
3
4
5 (stacksize-1)
// ……Program for stack implementation
#include <iostream>
using namespace std;
// here add all the initializations and
//functions’ definitions of stack.
int main()
{
push(9);
push(7);
push (8);
push (4);
pop ( );
push (5);
pop ( );
pop ( );
cout<< " top element of stack is = " << top() << endl;
bout << " top index is = " << top << endl;
}
top = 2
stack
9
7
8
?
?
?
0
1
2
3
4
5 (stacksize-1)
// ……Program for stack implementation
#include <iostream>
using namespace std;
// here add all the initializations and
//functions’ definitions of stack.
int main()
{
push(9);
push(7);
push (8);
push (4);
pop ( );
push (5);
pop ( );
pop ( );
cout<< " top element of stack is = " << top() << endl;
bout << " top index is = " << top << endl;
}
top = 2
stack
9
7
8
5
?
?
0
1
2
3
4
5 (stacksize-1)
// ……Program for stack implementation
#include <iostream>
using namespace std;
// here add all the initializations and
//functions’ definitions of stack.
int main()
{
push(9);
push(7);
push (8);
push (4);
pop ( );
push (5);
pop ( );
pop ( );
cout<< " top element of stack is = " << top() << endl;
bout << " top index is = " << top << endl;
}
top element of stack is = 7
top index is = 1
top = 2
stack
9
7
?
?
0
1
2
3
4
5 (stacksize-1)
28
Traversing a stack
void show()
{
int i;
for(i=top; i>=0; i--)
cout<< “ “<<stack[i];
}
OUTPUT:
D C B A
A
B
C
D
?
?
top
0
1
2
3
Stack[ ]
Stack
int Stack[100], Top=-1; // Stack holds the elements;
// Top is the index of Stack always pointing to the
first/top element of the stack.
bool IsEmpty( void ); // returns True if stack has no
element
bool IsFull( void ); // returns True if stack full
bool Push( int Element ); // inserts Element at the top of
the stack
bool Pop( int *Element ); // deletes top element from stack
into Element
bool TopElement( int *Element ); // gives the top element
in Element
void Show( void ); // prints the whole stack
bool IsEmpty( void ){
// returns True if stack has no element
return (Top < 0);
}
6
5
4
3
2
1
0
Top
Considering Size = 7
bool IsFull( void ){
// returns True if stack full
return ( Top >= Size-1 );
}
6 G
5 F
4 E
3 D
2 C
1 B
0 A
Top
Considering Size = 7
bool Push( int Element ){
// inserts Element at the top of the stack
if( IsFull( ) )
{ cout << "Stack is Fulln"; return false; }
// push element if there is space
Stack[ ++Top ] = Element;
return true;
}
6
5
4
3
2 C
1 B
0 A
Top
Considering Size = 7
There are 3 elements inside Stack
So next element will be pushed at index 3
bool Pop( int *Element ){
// deletes top element from stack and puts it in
Element
if( IsEmpty() )
{ cout << "Stack emptyn"; return false; }
*Element = Stack[ Top-- ];
return true;
}
6
5
4
3 D
2 C
1 B
0 A
Top
Considering Size = 7
There are 4 elements inside Stack
So element will be popped from index 3
bool TopElement( int *Element ){
// gives the top element in Element
if( IsEmpty() )
{ cout << "Stack emptyn"; return false; }
*Element = Stack[ Top ];
return true;
}
Considering Size = 7
There are 4 elements inside Stack
So top element will be at index 3
6
5
4
3 D
2 C
1 B
0 A
Top
void Show( void ){
// prints the whole stack
if( IsEmpty() )
{ cout << "Stack emptyn"; return; }
for( int i=Top; i>=0; i-- ) cout << Stack[i] <<endl;
}
6
5
4
3 D
2 C
1 B
0 A
Considering Size = 7
There are 4 elements inside Stack
So element will be shown from index
3 down to index 0.
Top
Creating a class for Stack
class MyStack{
int Stack[MaxSize], Top, MaxSize=100;
public:
//Initializing stack
MyStack( int Size = 100 ){ MaxSize = Size; Top = -1;}
bool IsEmpty( void );
bool IsFull( void );
bool Push( int Element );
bool Pop( int &Element );
bool TopElement( int &Element );
void Show( void );
void Reset( void ){ Top = -1; } //Re-start the stack
};
// ……Program for stack implementation using stack class
#include <iostream>
#include <stack>
using namespace std;
int main()
{ stack <int> st;
st.push(9);
st.push(7);
st.push (8);
st.push (9);
st.pop ( );
st.push (5);
st.pop ( );
st.pop ( );
cout<< " top element of stack is = " << st.top() << endl;
cout << " top index is = " << st.size()-1 << endl;
}
top element of stack is = 7
top index is = 1
Stack Using Dynamic Memory Allocation
class MyStack{
int *Stack, Top, MaxSize=100;
public:
MyStack( int );
~MyStack( void );
bool IsEmpty( void );
bool IsFull( void );
bool Push( int );
bool Pop( int & );
bool TopElement( int & );
void Show( void );
void Reset( void ){ Top = -1; }
void Resize( int ); //Resize the stack
};
The Constructor will create the array dynamically, Destructor will
release it.
MyStack::MyStack( int Size ){
MaxSize = Size; // get Size
Stack = new int[ MaxSize ]; // create array
acordingly
Top = 0; // start the stack
}
MyStack::~MyStack( void ){
delete [] Stack; // release the memory for
stack
}
Resize creates a new array dynamically, copies all the element from the
previous stack, releases the old array, and makes the pointer Stack point to
the new array.
 User can define the additional size. Use negative size to decrease the array.
void Resize( int Size ){
// creates a new stack with MaxSize + Size
int *S = new int[ MaxSize + Size ];
// copy the elements from old to new stack
for( int i=0; i<MaxSize; i++ ) S[i] = Stack[i];
MaxSize += Size; // MaxSize increases by Size
delete [] Stack; // release the old stack
this.Stack = S; // assign Stack with new stack.
}
void Push( int Element ){
// inserts Element at the top of the stack
if( StackFull( ) ) Resize( 5 ); // increase
size if full
Stack[ ++Top ] = Element;
}
Generic Stack
template <typename T>
class MyStack{
T *Stack;
int Top, MaxSize;
public:
MyStack( int );
~MyStack( void );
bool IsEmpty( void );
bool IsFull( void );
bool Push( const T );
bool Pop( T & );
bool TopElement( T & );
void Show( void );
void Reset( void ){ Top = 0; }
void Resize( int ); //Resize the stack
};
// ……Program for stack implementation using stack class (ADT)
#include <iostream>
#include <stack>
using namespace std;
int main()
{ stack <int> st;
st.push(9);
st.push(7);
st.push (8);
st.push (9);
st.pop ( );
st.push (5);
st.pop ( );
st.pop ( );
cout<< " top element of stack is = " << st.top() << endl;
cout << " top index is = " << st.size()-1 << endl;
}
top element of stack is = 7
top index is = 1
Application of stack continuation……
• Syntax parsing, Expression evaluation and
Expression conversion.
• Banking Transaction View
- You view the last transaction first.
• Backtracking and implementation of recursive
function, calling function.
• Towers of Hanoi
Validity checking of an arithmetic expression
When there is a opening parenthesis; brace or bracket,
there should be the corresponding closing parenthesis.
Otherwise, the expression is not a valid one. We can
check this validity using stack.
Stack in Problem Solving
• Consider a mathematical expression that includes several sets of
nested parenthesis, e.g
( x + (y – (a +b)) )
• We want to ensure that parenthesis are nested correctly and the
expression is valid
• Validation
1. There is an equal number of closing and opening parentheses
2. Every closing parenthesis is preceded by a matching opening
parenthesis
Algorithm
• Whenever an opening is encountered, PUSH() on to stack
• Whenever a closing is encountered,
– If stack is empty, expression is invalid.
– If stack is nonempty, POP() the stack and check with
corresponding closing parenthesis. If match occurs continue.
Otherwise expression is invalid.
• When the end of expression is reached, stack must be
empty; otherwise expression invalid.
Example:
[(A+B)-{(C+D)-E}]
Symbol Stack
[ [
( [(
A [(
+ [(
B [(
) [
- [
{ [{
( [{(
C [{(
+ [{(
D [{(
) [{
- [{
E [{
} [
]
Algebraic Expression
• An algebraic expression is a legal combination of operands and the
operators.
• Operand is the quantity (unit of data) on which a mathematical
operation is performed.
• Operand may be a variable like x, y, z or a constant like 5, 4,0,9,1 etc.
• Operator is a symbol which signifies a mathematical or logical
operation between the operands. Example of familiar operators
include +,-,*, /, ^ , %
• Considering these definitions of operands and operators now we can
write an example of expression as
x+y*z
Infix, Postfix and Prefix Expressions
• INFIX: From our schools times we have been familiar with the
expressions in which operands surround the operator, e.g. x+y, 6*3 etc
this way of writing the Expressions is called infix notation.
• POSTFIX: Postfix notation are also Known as Reverse Polish Notation
(RPN). They are different from the infix and prefix notations in the sense
that in the postfix notation, operator comes after the operands, e.g. xy+,
xyz+* etc.
• PREFIX: Prefix notation also Known as Polish notation. In the prefix
notation, as the name only suggests, operator comes before the
operands, e.g. +xy, *+xyz etc.
Operator Priorities
• How do you figure out the operands of an operator?
– a + b * c
– a * b + c / d
• This is done by assigning operator priorities.
priority(*) = priority(/) > priority(+) = priority(-)
• When an operand lies between two operators, the operand
associates with the operator that has higher priority.
Tie Breaker
• When an operand lies between two operators that have
the same priority, the operand associates with the
operator on the left.
– a * b / c / d
Delimiters
• Sub expression within delimiters is treated as a single
operand, independent from the remainder of the
expression.
– (a + b) * (c – d) / (e – f)
WHY PREFIX and POSTFIX ?
• Why to use these weird looking PREFIX
and POSTFIX notations when we have
simple INFIX notation?
Infix
• To our surprise INFIX notations are not as simple as they seem specially
while evaluating them. To evaluate an infix expression we need to
consider Operators’ Precedence and Associative property
• For example expression 3+5*4 evaluate to
32 = (3+5)*4 or
23 = 3+(5*4)
• Operator precedence and associativity governs the evaluation order of
an expression.
• An operator with higher precedence is applied before an operator
with lower precedence.
• Same precedence order operator is evaluated according to their
associativity order.
Operator Precedence and Associativity
Precedence Operator Associativity
1 :: Left-to-right
2 () [] . -> ++ -- Left-to-right
3
++ -- ~ ! sizeof new
delete
Right-to-left
* &
+ -
4 (type) Right-to-left
5 .* ->* Left-to-right
6 * / % Left-to-right
7 + - Left-to-right
8 << >> Left-to-right
Precedence Operator Associativity
9 < > <= >= Left-to-right
10 == != Left-to-right
11 & Left-to-right
12 ^ Left-to-right
13 | Left-to-right
14 && Left-to-right
15 || Left-to-right
16 ?: Right-to-left
17
= *= /= %= += -=
>>= <<= &= ^= |=
Right-to-left
18 , Left-to-right
What is associativity (for an operator) and
why is it important?
For operators, associativity means that when the same operator appears in a
row, then which operator occurrence we apply first.
It's important, since it changes the meaning of an expression. Consider the
division operator with integer arithmetic, which is left associative
4 / 2 / 3 <=> (4 / 2) / 3 <=> 2 / 3 = 0
If it were right associative, it would evaluate to an undefined expression, since
you would divide by zero
4 / 2 / 3 <=> 4 / (2 / 3) <=> 4 / 0 = undefined
Infix Expression Is Hard To Parse
• Need operator priorities, tie breaker, and delimiters.
• This makes computer evaluation more difficult than is
necessary.
• Postfix and prefix expression forms do not rely on operator
priorities, a tie breaker, or delimiters.
• So it is easier to evaluate expressions that are in these forms.
Both prefix and postfix notations have an advantage over infix that while
evaluating an expression in prefix or postfix form we need not consider
the Priority and Associative property (order of brackets).
–E.g. x/y*z becomes
–*/xyz in prefix and
–xy/z* in postfix.
Both prefix and postfix notations make Expression
Evaluation a lot easier.
When do we need to use them… 
• So, what is actually done in expression is scanned from user in
infix form; it is converted into prefix or postfix form and then
evaluated without considering the parenthesis and priority of
the operators.
Differences between Infix, Postfix and Prefix
• Infix notation is easy to read for humans, whereas pre-/postfix
notation is easier to parse for a machine.
• The big advantage in pre-/postfix notation is that there never
arise any questions like operator precedence.
Differences between Infix, Postfix and Prefix
• Infix is more human-readable. That's why it is very commonly used in
mathematics books.
• Infix has to add more information to remove ambiguity. So, for
example, we use parenthesis to give preference to lower precedence
operator.
• Postfix and Prefix are more machine-readable. So for instance, in
postfix, every time you encounter a number, put it on a stack, every
time you encounter an operator, pop the last two elements from the
stack, apply the operation and push the result back.
Examples of infix to prefix and postfix
Infix PostFix Prefix
A+B AB+ +AB
(A+B) * (C + D) AB+CD+* *+AB+CD
A-B/(C*D^E) ABCDE^*/- -A/B*C^DE
ABCDE^* / -
A - B/ ( C*D^E )
A- B/ ( C*F )
A- B/G
A-H
I
ABCF* / - D E
^
C F
*
ABG/ -
B G
/
AH-
A H
-
I
- A/B*C^DE
D E
^
C F
*
B G
/
A H
-
I
- A/B*CF
- A/BG
- AH
Algorithm for Infix to Postfix conversion
1) Examine the ith element in the input, infix[i].
2) If it is operand, output it at kth location (push to postfix[k]).
3) else If it is opening parenthesis ‘(’, push it on stack.
4) else If it is a closing parenthesis ‘)’,
pop (operators) from stack and output to postfix[k] them until an opening
parenthesis ‘(’ is encountered in the top of stack.
pop and discard the opening parenthesis ‘(’ from stack.
5) else If it is an operator ‘+’, ‘-’, ‘*’, ‘/’, ‘%’ then
i) If stack is empty, push operator on stack.
ii) else If the top of stack is opening parenthesis ‘(’, push on stack
iii) else If it has higher priority than the top of stack, push on stack.
iv) else pop the operator from the stack and output it, repeat step 5
6) If there is more input in infix[], go to step 1
7) If there is no more input, pop the remaining operators to output.
3/7/2021 Dr. Kazi A. Kalpoma 66
Suppose we want to convert infix: 2*3/(2-1)+5*3 into Postfix form,
So, the Postfix Expression is 23*21-/53*+
2 Empty 2
* * 2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
3 +* 23*21-/53
Input (infix) Stack Output (Postfix)
* +* 23*21-/5
Empty 23*21-/53*+
*  StackTop( + )
push (-) to stack
/ = StackTop( * )
Push (*) to stack
Push (/) to stack
(
)
+ < StackTop( / )
Push (+) to stack
)
2 * 6 / ( 4 - 1 ) + 5 * 3
CONVERTING INFIX TO POSTFIX
Infix Expression: 2*6/(4-1)+5*3
Add ')' to the end of Infix; Push( '(' );
do{
OP = next symbol from left of Infix;
if OP is OPERAND then EnQueue( OP );
else if OP is OPERATOR then{
if OP = '(' then Push( OP );
else if OP = ')' then{
Pop( StackOperator );
while StackOperator != '(' do{
Enqueue( Stackoperator );
Pop( StackOperator );
}`
}else{
while Precedence( OP ) <= Precedence( TopElement( ) ) do{
Pop( StackOperator );
Enqueue( StackOperator );
}
Push( OP );
}
}while !IsEmpty( );
Infix
Postfix
Stack
2 * 6 / ( 4 - 1 ) + 5 * 3
2 6 * 4 1 - / 5 3 * +
* ( -
*
/
+
OPERATOR
OPERAND
End of Expression
(
)
Example
• ( 5 + 6) * 9 +3
will be
• 5 6 + 9 * 3 +
Conversion of infix to prefix??
Algorithm for Infix to Postfix conversion
1) Examine the ith element in the input, infix[i].
2) If it is operand, output it at kth location (push to postfix[k]).
3) else If it is opening parenthesis ‘(’, push it on stack.
4) else If it is a closing parenthesis ‘)’,
pop (operators) from stack and output to postfix[k] them until an opening
parenthesis ‘(’ is encountered in the top of stack.
pop and discard the opening parenthesis ‘(’ from stack.
5) else If it is an operator ‘+’, ‘-’, ‘*’, ‘/’, ‘%’ then
i) If stack is empty, push operator on stack.
ii) else If the top of stack is opening parenthesis ‘(’, push on stack
iii) else If it has higher priority than the top of stack, push on stack.
iv) else pop the operator from the stack and output it, repeat step 5
6) If there is more input in infix[], go to step 1
7) If there is no more input, pop the remaining operators to output.
Input Output_stack Stack
) EMPTY )
G G )
+ G )+
F GF )+
( GF+ EMPTY
- GF+ -
) GF+ -)
) GF+ -))
E GF+E -))
+ GF+E -))+
D GF+ED -))+
( GF+ED+ -)
* GF+ED+ -)*
C GF+ED+C -)*
+ GF+ED+C* -)+
) GF+ED+C* -)+)
B GF+ED+C*B -)+)
- GF+ED+C*B -)+)-
A GF+ED+C*BA -)+)-
( GF+ED+C*BA- -)+
( GF+ED+C*BA-+ -
EMPTY GF+ED+C*BA-+- EMPTY
We have infix expression in the form of:
((A-B)+C*(D+E))-(F+G)
Now reading expression from right to left and
pushing operators into stack and variables to
output stack.
Out put_stack = GF+ED+C*BA-+-
Reversing the output_stack we get
prefix expression: -+-AB*C+DE+FG
Infix to Prefix conversion
Evaluating Postfix Notation
• Use a stack to evaluate an expression in postfix
notation.
• The postfix expression to be evaluated is scanned
from left to right.
• Variables or constants are pushed onto the stack.
• When an operator is encountered, the indicated
action is performed using the top elements of the
stack, and the result replaces the operands on the
stack.
Algorithm: To evaluate a postfix value
1. Add “)” at the right end of the expression. (this is just to know when to stop)
2. Scan p from left to right and repeat step 3 and 4 for each element
of p until encountered “)”.
3. If an operand is encountered, PUSH it in stack.
4. If an operator  is encountered, then
1. To remove two element from stack Call POP() twice and first POP() put to A
and second one to B.
2. Evaluate C = B  A.
3. PUSH(C) in stack.
5. Set the value = POP(), the top element of stack.
6. Exit
Postfix expressions:
Algorithm using stacks (cont.)
Question : Evaluate the following
expression in postfix :
623+-382/+*2^3+
Final answer is ?
Evaluate- 623+-382/+*2^3+ )
623+-382/+*2^3+)
65-382/+*2^3+) 1382/+*2^3+)
6
2
6
3
2
6
5
6
1
3
1
8
3
1
2
8
3
1
4
3
1
Cont. of Evaluation- 623+-382/+*2^3+
134+*2^3+)
72^3+) 493+)
)
= 52
4
3
1
7
1
7
2
7 49
3
49 52
2 6 * 4 1 - / 5 3 * + )
EVALUATING POSTFIX EXPRESSION
Postfix Expression: 26*41-/53*+
EnQueue( ')' );
while ( FrontElement( ) != ')' ){
DeQueue( OP );
if OP is OPERAND then Push( OP );
else if OP is OPERATOR then{
Pop( OperandRight );
Pop( OperandLeft );
Push( Evaluate( OperandLeft, OP, OperandRight ) );
}
}
Pop( Result );
cout << Result;
}
Postfix
Stack
2 6 * 4 1 - / 5 3 * +
2 4 1
3
6
12
OPERATOR
OPERAND
Evaluate( 2, '*', 6 ) = 12
Evaluate( 4, '+', 15 ) = 19
‘)‘
Evaluate( 5, '*', 3 ) = 15
Evaluate( 12, '/', 3 ) = 4
Evaluate( 4, '-', 1 ) = 3
End of Expression
)
4 5 3
15
19
Expression Result = 19
Algorithm: To evaluate a prefix value
1. Add “(” at the left end of the expression.
2. Scan p from right to left and repeat step 3 and 4 for
each element of p until encountered “(”.
3. If an operand is encountered, PUSH it in stack.
4. If an operator  is encountered, then
1. To remove two element from stack Call POP() twice and
first POP() put to A and second one to B.
2. Evaluate C = A  B
3. PUSH(C) in stack.
5. Set the value = POP(), the top element of stack.
6. Exit
3/7/2021 82
• Abstract Meaning:
* Existing in thought or as an idea but not having a physical or concrete existence.
* Consider something theoretically or separately from (something else).
* A summary of the contents of a book, article, or speech.

Contenu connexe

Tendances (20)

Queue ppt
Queue pptQueue ppt
Queue ppt
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Stack
StackStack
Stack
 
Stacks
StacksStacks
Stacks
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
Stack
StackStack
Stack
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Stack - Data Structure
Stack - Data StructureStack - Data Structure
Stack - Data Structure
 
Stack application
Stack applicationStack application
Stack application
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Insertion sort algorithm power point presentation
Insertion  sort algorithm power point presentation Insertion  sort algorithm power point presentation
Insertion sort algorithm power point presentation
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stack
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 

Similaire à Stack and its applications

Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magenvenaymagen19
 
CS8391-Data Structures Unit 2
CS8391-Data Structures Unit 2CS8391-Data Structures Unit 2
CS8391-Data Structures Unit 2SIMONTHOMAS S
 
DSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUEDSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUEswathirajstar
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptxHalid Assen
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptxSajalFayyaz
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationRAtna29
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7Kumar
 
13 Stacks and Queues.pptx
13 Stacks and Queues.pptx13 Stacks and Queues.pptx
13 Stacks and Queues.pptxssuserb7c8b8
 

Similaire à Stack and its applications (20)

04 stacks
04 stacks04 stacks
04 stacks
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Stack
StackStack
Stack
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 
CS8391-Data Structures Unit 2
CS8391-Data Structures Unit 2CS8391-Data Structures Unit 2
CS8391-Data Structures Unit 2
 
DS- Stack ADT
DS- Stack ADTDS- Stack ADT
DS- Stack ADT
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
MO 2020 DS Stacks 1 AB.ppt
MO 2020 DS Stacks 1 AB.pptMO 2020 DS Stacks 1 AB.ppt
MO 2020 DS Stacks 1 AB.ppt
 
DSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUEDSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUE
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptx
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
13 Stacks and Queues.pptx
13 Stacks and Queues.pptx13 Stacks and Queues.pptx
13 Stacks and Queues.pptx
 

Dernier

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 

Dernier (20)

week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 

Stack and its applications

  • 2. 2 Stack data structure Stack data structure is like a container with a single opening. • Can only access element at the top • Add/insert new items at the top • Remove/delete an item from the top Stack in real life: • collection of elements arranged in a linear order. - stack of books, stack of plates, stack of chairs.
  • 3. 3 A stack is open at one end (the top) only. You can push entry onto the top, or pop the top entry out of the stack. Note that you cannot add/extract entry in the middle of the stack. Stack A B C bottom top push pop
  • 4. 4 Last-in First-out (LIFO) A A B A B C When we insert entries onto the stack and then remove them out one by one, we will get the entries in reverse order. The last one inserted in is the first one removed out! (LIFO) A A B Insert(A); Insert(B); Insert(C); Remove(); Remove(); Remove(); A B C C C B A
  • 5. Stack • A stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: • Push: adds an element to the collection; • Pop: removes the last (top of the stack) element that was added. • Bounded capacity • If the stack is full and does not contain enough space to accept an entity to be pushed, the stack is then considered to be in an overflow state. • A pop either reveals previously concealed items or results in an empty stack – which means no items are present in stack to be removed. • Non-Bounded capacity • Dynamically allocate memory for stack. No overflow.
  • 6. Abstract Data Type (ADT) • An abstract data type is a type with associated operations, but whose representation is hidden. • The basic idea is that the implementation of these operations is written once in the program, and any other part of the program that needs to perform an operation on the ADT can do so by calling the appropriate function. • If for some reason implementation details need to change, it should be easy to do so by merely changing the routines that perform the ADT operations. This change, in a perfect world, would be completely transparent to the rest of the program.
  • 7. Abstract Data Type (ADT) • A data type whose properties (domain and operations) are specified independently of any particular implementation. • ADT is a mathematical model which gives a set of utilities available to the user but never states the details of its implementation. • In OO-Programming a Class is an ADT.
  • 8. • Let us consider Gmail. We can do lot of operation with Gmail such as Create Account, Sign in, Compose, Send, etc., We know the required details to Create an account.
  • 9. • But we don't know how these operations are functioning in background. • We don't know how Google team handling these operation to give you the required output. • Implementation of operation is always hidden to the user.
  • 10. • Let us assume Gmail as abstract data type. We can say Gmail is an object with operations such as create account, sign in, compose, send, etc.,
  • 12. Dr. Kazi A. Kalpoma
  • 13.
  • 14.
  • 15.
  • 16. 16 Stack Operations • Push(X) – insert element X at the top of the stack and increment the top index. • Pop() – remove the element from the top of the stack with/without returning element and decrement the top index. • Top() – return the top element without removing it from the stack. top index does not change.
  • 17. #define stack_size 6; int top; char stack[stack_size]; stack implementation by an array top = 2 stack stack ? ? ? ? ? ? 0 1 2 3 4 5 (stacksize-1)
  • 18. Initialization of top index of Stack stack_initialize() { top = -1; } ? ? ? ? ? ? top = 0 E--1ntry top 0 1 2 3 4 5 (stacksize-1)
  • 19. 19 Push(X) void push(char X) { if(top >= stack_size-1) cout<<“Overflow: stack is full”; else { top++; /increase top by 1 stack[top] = X; /insert the item on top } } X ? ? ? ? ? top= 0 1 entry top top++; stack[top] = X; Stack[++top] = X; 0 1 2 3 4 5 (stacksize-1) Before insertion it needs first to check the overflow situation i.e. stack is full or not full
  • 20. Pop() void pop() //pop function is not returning { if(top<0) cout<<"underflow: stack is empty”; else { char X = stack[top]; top--; } } top= 10 entry top ? ? ? ? ? ? 0 1 2 3 4 5 E--1ntry Before deletion it needs first to check the underflow situation i.e. stack is empty or not empty char X = stack[top]; top--; char X = stack[top--];
  • 21. Pop() //pop function is returning the top element char pop() { if(top<0) cout<<"underflow: stack is empty”; else { char X = stack[top]; top--; return X; } } top= 10 entry top ? ? ? ? ? ? 0 1 2 3 4 5 E--1ntry
  • 22. Top() char Top() //top function is returning top value { return stack[top]; //but not reduce top index } top= 10 entry top K R ? ? ? ? 0 1 2 3 4 5
  • 23. 23 Other operations int IsEmpty() { return ( top < 0 ); } int IsFull() { return ( top >= stack_size-1); } top = 2 stack ? ? ? ? ? ? 0 1 2 3 4 5 (stacksize-1)
  • 24. // ……Program for stack implementation #include <iostream> using namespace std; // here add all the initializations and //functions’ definitions of stack. int main() { push(9); push(7); push (8); push (4); pop ( ); push (5); pop ( ); pop ( ); cout<< " top element of stack is = " << top() << endl; cout << " top index is = " << top << endl; } top = 2 stack 9 7 8 4 ? ? 0 1 2 3 4 5 (stacksize-1)
  • 25. // ……Program for stack implementation #include <iostream> using namespace std; // here add all the initializations and //functions’ definitions of stack. int main() { push(9); push(7); push (8); push (4); pop ( ); push (5); pop ( ); pop ( ); cout<< " top element of stack is = " << top() << endl; bout << " top index is = " << top << endl; } top = 2 stack 9 7 8 ? ? ? 0 1 2 3 4 5 (stacksize-1)
  • 26. // ……Program for stack implementation #include <iostream> using namespace std; // here add all the initializations and //functions’ definitions of stack. int main() { push(9); push(7); push (8); push (4); pop ( ); push (5); pop ( ); pop ( ); cout<< " top element of stack is = " << top() << endl; bout << " top index is = " << top << endl; } top = 2 stack 9 7 8 5 ? ? 0 1 2 3 4 5 (stacksize-1)
  • 27. // ……Program for stack implementation #include <iostream> using namespace std; // here add all the initializations and //functions’ definitions of stack. int main() { push(9); push(7); push (8); push (4); pop ( ); push (5); pop ( ); pop ( ); cout<< " top element of stack is = " << top() << endl; bout << " top index is = " << top << endl; } top element of stack is = 7 top index is = 1 top = 2 stack 9 7 ? ? 0 1 2 3 4 5 (stacksize-1)
  • 28. 28 Traversing a stack void show() { int i; for(i=top; i>=0; i--) cout<< “ “<<stack[i]; } OUTPUT: D C B A A B C D ? ? top 0 1 2 3 Stack[ ]
  • 29. Stack int Stack[100], Top=-1; // Stack holds the elements; // Top is the index of Stack always pointing to the first/top element of the stack. bool IsEmpty( void ); // returns True if stack has no element bool IsFull( void ); // returns True if stack full bool Push( int Element ); // inserts Element at the top of the stack bool Pop( int *Element ); // deletes top element from stack into Element bool TopElement( int *Element ); // gives the top element in Element void Show( void ); // prints the whole stack
  • 30. bool IsEmpty( void ){ // returns True if stack has no element return (Top < 0); } 6 5 4 3 2 1 0 Top Considering Size = 7
  • 31. bool IsFull( void ){ // returns True if stack full return ( Top >= Size-1 ); } 6 G 5 F 4 E 3 D 2 C 1 B 0 A Top Considering Size = 7
  • 32. bool Push( int Element ){ // inserts Element at the top of the stack if( IsFull( ) ) { cout << "Stack is Fulln"; return false; } // push element if there is space Stack[ ++Top ] = Element; return true; } 6 5 4 3 2 C 1 B 0 A Top Considering Size = 7 There are 3 elements inside Stack So next element will be pushed at index 3
  • 33. bool Pop( int *Element ){ // deletes top element from stack and puts it in Element if( IsEmpty() ) { cout << "Stack emptyn"; return false; } *Element = Stack[ Top-- ]; return true; } 6 5 4 3 D 2 C 1 B 0 A Top Considering Size = 7 There are 4 elements inside Stack So element will be popped from index 3
  • 34. bool TopElement( int *Element ){ // gives the top element in Element if( IsEmpty() ) { cout << "Stack emptyn"; return false; } *Element = Stack[ Top ]; return true; } Considering Size = 7 There are 4 elements inside Stack So top element will be at index 3 6 5 4 3 D 2 C 1 B 0 A Top
  • 35. void Show( void ){ // prints the whole stack if( IsEmpty() ) { cout << "Stack emptyn"; return; } for( int i=Top; i>=0; i-- ) cout << Stack[i] <<endl; } 6 5 4 3 D 2 C 1 B 0 A Considering Size = 7 There are 4 elements inside Stack So element will be shown from index 3 down to index 0. Top
  • 36. Creating a class for Stack class MyStack{ int Stack[MaxSize], Top, MaxSize=100; public: //Initializing stack MyStack( int Size = 100 ){ MaxSize = Size; Top = -1;} bool IsEmpty( void ); bool IsFull( void ); bool Push( int Element ); bool Pop( int &Element ); bool TopElement( int &Element ); void Show( void ); void Reset( void ){ Top = -1; } //Re-start the stack };
  • 37. // ……Program for stack implementation using stack class #include <iostream> #include <stack> using namespace std; int main() { stack <int> st; st.push(9); st.push(7); st.push (8); st.push (9); st.pop ( ); st.push (5); st.pop ( ); st.pop ( ); cout<< " top element of stack is = " << st.top() << endl; cout << " top index is = " << st.size()-1 << endl; } top element of stack is = 7 top index is = 1
  • 38. Stack Using Dynamic Memory Allocation class MyStack{ int *Stack, Top, MaxSize=100; public: MyStack( int ); ~MyStack( void ); bool IsEmpty( void ); bool IsFull( void ); bool Push( int ); bool Pop( int & ); bool TopElement( int & ); void Show( void ); void Reset( void ){ Top = -1; } void Resize( int ); //Resize the stack };
  • 39. The Constructor will create the array dynamically, Destructor will release it. MyStack::MyStack( int Size ){ MaxSize = Size; // get Size Stack = new int[ MaxSize ]; // create array acordingly Top = 0; // start the stack } MyStack::~MyStack( void ){ delete [] Stack; // release the memory for stack }
  • 40. Resize creates a new array dynamically, copies all the element from the previous stack, releases the old array, and makes the pointer Stack point to the new array.  User can define the additional size. Use negative size to decrease the array. void Resize( int Size ){ // creates a new stack with MaxSize + Size int *S = new int[ MaxSize + Size ]; // copy the elements from old to new stack for( int i=0; i<MaxSize; i++ ) S[i] = Stack[i]; MaxSize += Size; // MaxSize increases by Size delete [] Stack; // release the old stack this.Stack = S; // assign Stack with new stack. }
  • 41. void Push( int Element ){ // inserts Element at the top of the stack if( StackFull( ) ) Resize( 5 ); // increase size if full Stack[ ++Top ] = Element; }
  • 42. Generic Stack template <typename T> class MyStack{ T *Stack; int Top, MaxSize; public: MyStack( int ); ~MyStack( void ); bool IsEmpty( void ); bool IsFull( void ); bool Push( const T ); bool Pop( T & ); bool TopElement( T & ); void Show( void ); void Reset( void ){ Top = 0; } void Resize( int ); //Resize the stack };
  • 43. // ……Program for stack implementation using stack class (ADT) #include <iostream> #include <stack> using namespace std; int main() { stack <int> st; st.push(9); st.push(7); st.push (8); st.push (9); st.pop ( ); st.push (5); st.pop ( ); st.pop ( ); cout<< " top element of stack is = " << st.top() << endl; cout << " top index is = " << st.size()-1 << endl; } top element of stack is = 7 top index is = 1
  • 44.
  • 45.
  • 46. Application of stack continuation…… • Syntax parsing, Expression evaluation and Expression conversion. • Banking Transaction View - You view the last transaction first. • Backtracking and implementation of recursive function, calling function. • Towers of Hanoi
  • 47. Validity checking of an arithmetic expression When there is a opening parenthesis; brace or bracket, there should be the corresponding closing parenthesis. Otherwise, the expression is not a valid one. We can check this validity using stack.
  • 48. Stack in Problem Solving • Consider a mathematical expression that includes several sets of nested parenthesis, e.g ( x + (y – (a +b)) ) • We want to ensure that parenthesis are nested correctly and the expression is valid • Validation 1. There is an equal number of closing and opening parentheses 2. Every closing parenthesis is preceded by a matching opening parenthesis
  • 49. Algorithm • Whenever an opening is encountered, PUSH() on to stack • Whenever a closing is encountered, – If stack is empty, expression is invalid. – If stack is nonempty, POP() the stack and check with corresponding closing parenthesis. If match occurs continue. Otherwise expression is invalid. • When the end of expression is reached, stack must be empty; otherwise expression invalid.
  • 50. Example: [(A+B)-{(C+D)-E}] Symbol Stack [ [ ( [( A [( + [( B [( ) [ - [ { [{ ( [{( C [{( + [{( D [{( ) [{ - [{ E [{ } [ ]
  • 51. Algebraic Expression • An algebraic expression is a legal combination of operands and the operators. • Operand is the quantity (unit of data) on which a mathematical operation is performed. • Operand may be a variable like x, y, z or a constant like 5, 4,0,9,1 etc. • Operator is a symbol which signifies a mathematical or logical operation between the operands. Example of familiar operators include +,-,*, /, ^ , % • Considering these definitions of operands and operators now we can write an example of expression as x+y*z
  • 52. Infix, Postfix and Prefix Expressions • INFIX: From our schools times we have been familiar with the expressions in which operands surround the operator, e.g. x+y, 6*3 etc this way of writing the Expressions is called infix notation. • POSTFIX: Postfix notation are also Known as Reverse Polish Notation (RPN). They are different from the infix and prefix notations in the sense that in the postfix notation, operator comes after the operands, e.g. xy+, xyz+* etc. • PREFIX: Prefix notation also Known as Polish notation. In the prefix notation, as the name only suggests, operator comes before the operands, e.g. +xy, *+xyz etc.
  • 53. Operator Priorities • How do you figure out the operands of an operator? – a + b * c – a * b + c / d • This is done by assigning operator priorities. priority(*) = priority(/) > priority(+) = priority(-) • When an operand lies between two operators, the operand associates with the operator that has higher priority.
  • 54. Tie Breaker • When an operand lies between two operators that have the same priority, the operand associates with the operator on the left. – a * b / c / d Delimiters • Sub expression within delimiters is treated as a single operand, independent from the remainder of the expression. – (a + b) * (c – d) / (e – f)
  • 55. WHY PREFIX and POSTFIX ? • Why to use these weird looking PREFIX and POSTFIX notations when we have simple INFIX notation?
  • 56. Infix • To our surprise INFIX notations are not as simple as they seem specially while evaluating them. To evaluate an infix expression we need to consider Operators’ Precedence and Associative property • For example expression 3+5*4 evaluate to 32 = (3+5)*4 or 23 = 3+(5*4) • Operator precedence and associativity governs the evaluation order of an expression. • An operator with higher precedence is applied before an operator with lower precedence. • Same precedence order operator is evaluated according to their associativity order.
  • 57. Operator Precedence and Associativity Precedence Operator Associativity 1 :: Left-to-right 2 () [] . -> ++ -- Left-to-right 3 ++ -- ~ ! sizeof new delete Right-to-left * & + - 4 (type) Right-to-left 5 .* ->* Left-to-right 6 * / % Left-to-right 7 + - Left-to-right 8 << >> Left-to-right Precedence Operator Associativity 9 < > <= >= Left-to-right 10 == != Left-to-right 11 & Left-to-right 12 ^ Left-to-right 13 | Left-to-right 14 && Left-to-right 15 || Left-to-right 16 ?: Right-to-left 17 = *= /= %= += -= >>= <<= &= ^= |= Right-to-left 18 , Left-to-right
  • 58. What is associativity (for an operator) and why is it important? For operators, associativity means that when the same operator appears in a row, then which operator occurrence we apply first. It's important, since it changes the meaning of an expression. Consider the division operator with integer arithmetic, which is left associative 4 / 2 / 3 <=> (4 / 2) / 3 <=> 2 / 3 = 0 If it were right associative, it would evaluate to an undefined expression, since you would divide by zero 4 / 2 / 3 <=> 4 / (2 / 3) <=> 4 / 0 = undefined
  • 59. Infix Expression Is Hard To Parse • Need operator priorities, tie breaker, and delimiters. • This makes computer evaluation more difficult than is necessary. • Postfix and prefix expression forms do not rely on operator priorities, a tie breaker, or delimiters. • So it is easier to evaluate expressions that are in these forms.
  • 60. Both prefix and postfix notations have an advantage over infix that while evaluating an expression in prefix or postfix form we need not consider the Priority and Associative property (order of brackets). –E.g. x/y*z becomes –*/xyz in prefix and –xy/z* in postfix. Both prefix and postfix notations make Expression Evaluation a lot easier.
  • 61. When do we need to use them…  • So, what is actually done in expression is scanned from user in infix form; it is converted into prefix or postfix form and then evaluated without considering the parenthesis and priority of the operators.
  • 62. Differences between Infix, Postfix and Prefix • Infix notation is easy to read for humans, whereas pre-/postfix notation is easier to parse for a machine. • The big advantage in pre-/postfix notation is that there never arise any questions like operator precedence.
  • 63. Differences between Infix, Postfix and Prefix • Infix is more human-readable. That's why it is very commonly used in mathematics books. • Infix has to add more information to remove ambiguity. So, for example, we use parenthesis to give preference to lower precedence operator. • Postfix and Prefix are more machine-readable. So for instance, in postfix, every time you encounter a number, put it on a stack, every time you encounter an operator, pop the last two elements from the stack, apply the operation and push the result back.
  • 64. Examples of infix to prefix and postfix Infix PostFix Prefix A+B AB+ +AB (A+B) * (C + D) AB+CD+* *+AB+CD A-B/(C*D^E) ABCDE^*/- -A/B*C^DE ABCDE^* / - A - B/ ( C*D^E ) A- B/ ( C*F ) A- B/G A-H I ABCF* / - D E ^ C F * ABG/ - B G / AH- A H - I - A/B*C^DE D E ^ C F * B G / A H - I - A/B*CF - A/BG - AH
  • 65. Algorithm for Infix to Postfix conversion 1) Examine the ith element in the input, infix[i]. 2) If it is operand, output it at kth location (push to postfix[k]). 3) else If it is opening parenthesis ‘(’, push it on stack. 4) else If it is a closing parenthesis ‘)’, pop (operators) from stack and output to postfix[k] them until an opening parenthesis ‘(’ is encountered in the top of stack. pop and discard the opening parenthesis ‘(’ from stack. 5) else If it is an operator ‘+’, ‘-’, ‘*’, ‘/’, ‘%’ then i) If stack is empty, push operator on stack. ii) else If the top of stack is opening parenthesis ‘(’, push on stack iii) else If it has higher priority than the top of stack, push on stack. iv) else pop the operator from the stack and output it, repeat step 5 6) If there is more input in infix[], go to step 1 7) If there is no more input, pop the remaining operators to output.
  • 66. 3/7/2021 Dr. Kazi A. Kalpoma 66
  • 67. Suppose we want to convert infix: 2*3/(2-1)+5*3 into Postfix form, So, the Postfix Expression is 23*21-/53*+ 2 Empty 2 * * 2 3 * 23 / / 23* ( /( 23* 2 /( 23*2 - /(- 23*2 1 /(- 23*21 ) / 23*21- + + 23*21-/ 5 + 23*21-/5 3 +* 23*21-/53 Input (infix) Stack Output (Postfix) * +* 23*21-/5 Empty 23*21-/53*+
  • 68. *  StackTop( + ) push (-) to stack / = StackTop( * ) Push (*) to stack Push (/) to stack ( ) + < StackTop( / ) Push (+) to stack ) 2 * 6 / ( 4 - 1 ) + 5 * 3 CONVERTING INFIX TO POSTFIX Infix Expression: 2*6/(4-1)+5*3 Add ')' to the end of Infix; Push( '(' ); do{ OP = next symbol from left of Infix; if OP is OPERAND then EnQueue( OP ); else if OP is OPERATOR then{ if OP = '(' then Push( OP ); else if OP = ')' then{ Pop( StackOperator ); while StackOperator != '(' do{ Enqueue( Stackoperator ); Pop( StackOperator ); }` }else{ while Precedence( OP ) <= Precedence( TopElement( ) ) do{ Pop( StackOperator ); Enqueue( StackOperator ); } Push( OP ); } }while !IsEmpty( ); Infix Postfix Stack 2 * 6 / ( 4 - 1 ) + 5 * 3 2 6 * 4 1 - / 5 3 * + * ( - * / + OPERATOR OPERAND End of Expression ( )
  • 69. Example • ( 5 + 6) * 9 +3 will be • 5 6 + 9 * 3 + Conversion of infix to prefix??
  • 70. Algorithm for Infix to Postfix conversion 1) Examine the ith element in the input, infix[i]. 2) If it is operand, output it at kth location (push to postfix[k]). 3) else If it is opening parenthesis ‘(’, push it on stack. 4) else If it is a closing parenthesis ‘)’, pop (operators) from stack and output to postfix[k] them until an opening parenthesis ‘(’ is encountered in the top of stack. pop and discard the opening parenthesis ‘(’ from stack. 5) else If it is an operator ‘+’, ‘-’, ‘*’, ‘/’, ‘%’ then i) If stack is empty, push operator on stack. ii) else If the top of stack is opening parenthesis ‘(’, push on stack iii) else If it has higher priority than the top of stack, push on stack. iv) else pop the operator from the stack and output it, repeat step 5 6) If there is more input in infix[], go to step 1 7) If there is no more input, pop the remaining operators to output.
  • 71. Input Output_stack Stack ) EMPTY ) G G ) + G )+ F GF )+ ( GF+ EMPTY - GF+ - ) GF+ -) ) GF+ -)) E GF+E -)) + GF+E -))+ D GF+ED -))+ ( GF+ED+ -) * GF+ED+ -)* C GF+ED+C -)* + GF+ED+C* -)+ ) GF+ED+C* -)+) B GF+ED+C*B -)+) - GF+ED+C*B -)+)- A GF+ED+C*BA -)+)- ( GF+ED+C*BA- -)+ ( GF+ED+C*BA-+ - EMPTY GF+ED+C*BA-+- EMPTY We have infix expression in the form of: ((A-B)+C*(D+E))-(F+G) Now reading expression from right to left and pushing operators into stack and variables to output stack. Out put_stack = GF+ED+C*BA-+- Reversing the output_stack we get prefix expression: -+-AB*C+DE+FG Infix to Prefix conversion
  • 72. Evaluating Postfix Notation • Use a stack to evaluate an expression in postfix notation. • The postfix expression to be evaluated is scanned from left to right. • Variables or constants are pushed onto the stack. • When an operator is encountered, the indicated action is performed using the top elements of the stack, and the result replaces the operands on the stack.
  • 73. Algorithm: To evaluate a postfix value 1. Add “)” at the right end of the expression. (this is just to know when to stop) 2. Scan p from left to right and repeat step 3 and 4 for each element of p until encountered “)”. 3. If an operand is encountered, PUSH it in stack. 4. If an operator  is encountered, then 1. To remove two element from stack Call POP() twice and first POP() put to A and second one to B. 2. Evaluate C = B  A. 3. PUSH(C) in stack. 5. Set the value = POP(), the top element of stack. 6. Exit
  • 75. Question : Evaluate the following expression in postfix : 623+-382/+*2^3+ Final answer is ?
  • 76. Evaluate- 623+-382/+*2^3+ ) 623+-382/+*2^3+) 65-382/+*2^3+) 1382/+*2^3+) 6 2 6 3 2 6 5 6 1 3 1 8 3 1 2 8 3 1 4 3 1
  • 77. Cont. of Evaluation- 623+-382/+*2^3+ 134+*2^3+) 72^3+) 493+) ) = 52 4 3 1 7 1 7 2 7 49 3 49 52
  • 78.
  • 79. 2 6 * 4 1 - / 5 3 * + ) EVALUATING POSTFIX EXPRESSION Postfix Expression: 26*41-/53*+ EnQueue( ')' ); while ( FrontElement( ) != ')' ){ DeQueue( OP ); if OP is OPERAND then Push( OP ); else if OP is OPERATOR then{ Pop( OperandRight ); Pop( OperandLeft ); Push( Evaluate( OperandLeft, OP, OperandRight ) ); } } Pop( Result ); cout << Result; } Postfix Stack 2 6 * 4 1 - / 5 3 * + 2 4 1 3 6 12 OPERATOR OPERAND Evaluate( 2, '*', 6 ) = 12 Evaluate( 4, '+', 15 ) = 19 ‘)‘ Evaluate( 5, '*', 3 ) = 15 Evaluate( 12, '/', 3 ) = 4 Evaluate( 4, '-', 1 ) = 3 End of Expression ) 4 5 3 15 19 Expression Result = 19
  • 80. Algorithm: To evaluate a prefix value 1. Add “(” at the left end of the expression. 2. Scan p from right to left and repeat step 3 and 4 for each element of p until encountered “(”. 3. If an operand is encountered, PUSH it in stack. 4. If an operator  is encountered, then 1. To remove two element from stack Call POP() twice and first POP() put to A and second one to B. 2. Evaluate C = A  B 3. PUSH(C) in stack. 5. Set the value = POP(), the top element of stack. 6. Exit
  • 81.
  • 83. • Abstract Meaning: * Existing in thought or as an idea but not having a physical or concrete existence. * Consider something theoretically or separately from (something else). * A summary of the contents of a book, article, or speech.