SlideShare a Scribd company logo
Data Structure
Lecture No. 8
Infix to Postfix
Conversion
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chishti
International Islamic University H-10, Islamabad, Pakistan
Video Lecture
 Consider the infix expressions A+B*C and (A+B)*C.
 The postfix versions are ABC*+ and AB+C*.
 The order of operands in postfix is the same as the infix.
 In scanning from left to right
 The operand ‘A’ can be inserted into postfix expression.
 The ‘+’ cannot be inserted until its second operand has been scanned and
inserted.
 The ‘+’ has to be stored away until its proper position is found.
 When ‘B’ is seen, it is immediately inserted into the postfix expression.
 Can the ‘+’ be inserted now? In the case of A+B*C cannot because * has
precedence.
 In case of (A+B)*C, the closing parenthesis indicates that ‘+’ must be
performed first.
Converting Infix to Postfix
 So we set priority to each
operator.
Operator Priority
^ 3(highest)
/, * 2
+, - 1 (lowest)
 Here is the algorithm that converts
infix expression to its postfix form.
 The infix expression is without
parenthesis.
Converting Infix to Postfix
1. Stack s;
2. while( not end of input ) {
3. c = next input character;
4. if( c is an operand )
5. add c to postfix string;
6. else {
7. while(!s.empty() && pr(c)<= pr(s.top())
8. {
9. op = s.pop();
10. add op to the postfix string;
11. }
12. s.push( c );
13. }
14. while( !s.empty() ) {
15. op = s.pop();
16. add op to postfix string;
17. }
 Example: A + B * C
Symb postfix stack
A A
+ A +
B AB +
* AB + *
C ABC + *
ABC * +
ABC * +
Infix to Postfix Example
 Read all the symbols one by one from left to
right in the given Infix Expression.
 If the reading symbol is operand, then directly
print it to the result (Output).
 If the reading symbol is left parenthesis '(', then
Push it on to the Stack.
 If the reading symbol is right parenthesis ')',
then Pop all the contents of stack until
respective left parenthesis is poped and print
each poped symbol to the result.
 If the reading symbol is operator (+ , - , * , /
etc.,), then Push it on to the Stack. However, first
pop the operators which are already on the
stack that have higher or equal precedence than
current operator and print them to the result.
 Example: A ^ B * C - D + E / F
Infix to Postfix Example
Symbol Stack Postfix Comments
A A A is operand
^ ^ A ^ is operator
B ^ A B B is operand
* A B ^ (* <= ^) = true, pop ^
* A B ^ stack is empty so push *
C * A B ^ C C is operand
– A B ^ C * (- <= *) = true, pop *
– A B ^ C * stack is empty so push –
D – A B ^ C * D D is operand
+ A B ^ C * D – (+ <= -) = true, pop –
+ A B ^ C * D – stack is empty so push +
 Example: A ^ B * - D + E / F
Infix to Postfix Example
Symbol Stack Postfix Comments
E + A B ^ C * D – E E is operand
/ + / A B ^ C * D – E (/ <= +) = false, push /
F + / A B ^ C * D – E F F is operand
+ A B ^ C * D – E F / pop /
A B ^ C * D – E F / + pop +
#include <iostream>
#include <string.h>
using namespace std;
typedef int Type;
struct Node{
Type data ;
Node * next ;
};
class Stack{
private : Node* head;
public : Stack( );
bool Is_Empty();
Type Top();
void Push ( Type Data );
Type Pop ( );
~Stack( ) ;
};
Stack::Stack( ){ head = NULL; }
7
Example 1: Infix to Postfix
bool Stack::Is_Empty() {
return head == NULL;
}
Type Stack::Top() {
if ( !Is_Empty() )
return head->data;
return -1;
}
void Stack :: Push ( Type Data ) {
Node *newNode ;
newNode = new Node ;
if ( newNode == NULL ){
cout << endl << "Stack is full" ;
return;
}
newNode -> data = Data ;
newNode -> next = head ;
head = newNode ;
}
1 2
Type Stack :: Pop( ) {
if ( Is_Empty() ){
cout << "Stack is empty " ;
return -1 ;
}
Node *current ;
Type Data ;
current = head ;
Data = current -> data ;
head = head -> next ;
delete current ;
return Data ;
}
Stack :: ~Stack( ){
Node *current ;
while ( head != NULL ){
current = head ;
head = head -> next ;
delete head ;
8
Example 1: Infix to Postfix
}
}
class In2Post{
private: Stack s; char* expr;
public:
In2Post(char eq[]);
bool Is_Operand(char op);
int Priority (char op);
void Convert();
};
In2Post::In2Post(char eq[]) {
expr = new char[strlen(eq) + 1];
strcpy(expr,eq);
}
3 4
bool In2Post::Is_Operand(char op){
switch(op){
case '+': return false;
case '-': return false;
case '*': return false;
case '/': return false;
case '^': return false;
default: return true;
}
}
int In2Post::Priority (char op){
switch(op){
case '^': return 3;
case '*':
case '/': return 2 ;
case '+':
case '-': return 1 ;
default : return 0; } }
9
Example 1: Infix to Postfix
void In2Post::Convert(){
char c, p;
for ( int i =0 ; expr[i] ; i++){
c = expr[i];
if ( c == ' ' || c == 't' )
continue ;
if ( Is_Operand(c))
cout << c <<" ";
else{
while( !s.Is_Empty() &&
(Priority(c) <= Priority(s.Top())) )
{
p = s.Pop();
cout << p << " ";
}
s.Push( c );
}
}
5 6
while( !s.Is_Empty() ) {
c = s.Pop();
cout << c <<" ";
}
}
int main( ){
char expression [] =
// {"A+B*C"}; // A B C * +
// {"A+B-C"}; // A B + C -
{"A ^ B * C - D + E / F"};
// A B ^ C * D – E F / +
In2Post I2P(expression);
I2P.Convert();
cout << endl;
system("PAUSE");
return 0;
}
10
Example 1: Infix to Postfix
7 8
 Example: A + ( B * C - ( D / E ^ F ) * G ) * H
Infix to Postfix Example with Parenthesis
Symbol Stack Postfix Comments
A A A is operand
+ + A Stack is empty, push +
( + ( A Push (
B + ( A B B is operand
* + ( * A B ( * <= ( ) = false, push *
C + ( * A B C C is operand
– + ( A B C * ( - <= * ) = true, pop *
+ ( – A B C * ( - <= ( ) = false, push –
( + ( – ( A B C * push (
D + ( – ( A B C * D D is operand
/ + ( – ( / A B C * D ( / <= ( ) = false, push /
E + ( – ( / A B C * D E E is operand
^ + ( – ( / ^ A B C * D E ( ^ <= / ) = false, push ^
 Example: A + ( B * C - ( D / E ^ F ) * G ) * H
Infix to Postfix Example with Parenthesis
Symbol Stack Postfix Comments
F + ( – ( / ^ A B C * D E F F is operand
) + ( – ( / A B C * D E F ^ pop until we get (
+ ( – ( A B C * D E F ^ / pop until we get (
+ ( – A B C * D E F ^ / pop until we get (
* + ( – * A B C * D E F ^ / ( * <= - ) = false, push *
G + ( – * A B C * D E F ^ / G G is operand
) + ( – A B C * D E F ^ / G * pop until we get (
+ ( A B C * D E F ^ / G * - pop until we get (
+ A B C * D E F ^ / G * - pop until we get (
* + * A B C * D E F ^ / G * - ( * <= + ) = false, push *
H + * A B C * D E F ^ / G * - H H is operand
+ A B C * D E F ^ / G * - H * pop until stack is empty
A B C * D E F ^ / G * - H * + pop until stack is empty
#include <iostream>
#include <math.h> // for pow( , )
using namespace std;
typedef char Type;
class Stack{
private :
struct node{
Type data ;
node * next ;
} *head;
public :
Stack( ) { head = NULL ; }
Type top() { return head->data; }
bool IsEmpty();
void Push ( Type Data );
Type Pop ( );
~Stack( ) ;
};
13
Example 2: Infix to Postfix with Parenthesis
bool Stack::IsEmpty(){
return head ==NULL;
}
void Stack :: Push ( Type Data ) {
node *newNode ;
newNode = new node ;
if ( newNode == NULL ){
cout << endl << "Stack is full" ;
return;
}
newNode -> data = Data ;
newNode -> next = head ;
head = newNode ;
}
1 2
Type Stack :: Pop( ) {
if ( IsEmpty() ){
cout << "Stack is empty " ;
return -1 ;
}
node *current ; Type Data ;
current = head ;
Data = current -> data ;
head = head -> next ;
delete current ;
return Data ;
}
// deallocates memory
Stack :: ~Stack( ){
node *current ;
while ( head != NULL ){
current = head ;
head = head -> next ;
14
Example 2: Infix to Postfix with Parenthesis
delete head ;
}
}
class In2Post {
private:
Stack s;
char* expr;
public:
In2Post(char eq[]);
bool is_operand(char op);
int Priority (char op);
void Convert();
};
In2Post::In2Post(char eq[]) {
expr = new char[strlen(eq) + 1];
strcpy(expr,eq);
}
3 4
bool In2Post :: is_operand(char op){
switch(op){
case '+': return false;
case '-': return false;
case '*': return false;
case '/': return false;
case '^': return false;
case '(': return false;
case ')': return false;
default : return true ;
}
}
15
Example 2: Infix to Postfix with Parenthesis
int In2Post::Priority (char op){
switch(op){
case '^': return 3;
case '*':
case '/': return 2 ;
case '+':
case '-': return 1 ;
default : return 0;
}
}
5 6
void In2Post::Convert(){
char c, p;
for ( int i =0 ; expr[i] ; i++){
c = expr[i];
if ( c == ' ' || c == 't' )
continue ;
else if ( is_operand(c))
cout << c <<" ";
else if(c=='(' )
s.Push( c );
else if(c==')' ){
while( true ){
p = s.Pop();
if( p == '(')
break;
else
cout << p <<" ";
}
}
16
Example 2: Infix to Postfix with Parenthesis
else{
while( !s.IsEmpty() &&
(Priority(c) <= Priority(s.top()))) {
p = s.Pop();
if( p !=')' && p !='(')
cout << p << " ";
}
s.Push( c );
}
}
while( !s.IsEmpty() ) {
p = s.Pop();
if( p !=')' && p !='(')
cout << p << " ";
}
}
7 8
int main( ){
char expression [] =
// {"A+B*C"}; // ABC*+
// {"A+B-C"}; // AB+C-
// {"A^B*C-D+E/F"};
// = A B ^ C*D – E F/+
// {"(A+B)*(C-D)"};
// = A B + C D - *
// {"(A+B)*C"}; // ABC*+
{" A + ( B * C - ( D / E ^ F )"
" * G ) * H "};
// = A B C * D E F ^ / G * - H * +
In2Post I2P(expression);
I2P.Convert();
cout << endl;
system("PAUSE"); return 0;
}
17
Example 2: Infix to Postfix with Parenthesis
9 10

More Related Content

Similar to Data Structures and Agorithm: DS 08 Infix to Postfix.pptx

Stack
StackStack
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
Expression evaluation
Expression evaluationExpression evaluation
Expression evaluation
JeeSa Sultana
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
maamir farooq
 
Stack
StackStack
Data structures
Data structures Data structures
Data structures
Rokonuzzaman Rony
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
A. S. M. Shafi
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
week-18x
week-18xweek-18x
week-17x
week-17xweek-17x
stacks and queues
stacks and queuesstacks and queues
stacks and queues
DurgaDeviCbit
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
mohdjakirfb
 
Stack and queue
Stack and queueStack and queue
Stack and queue
Shakila Mahjabin
 
Applicationofstack by Ali F.RAshid
Applicationofstack  by Ali F.RAshid Applicationofstack  by Ali F.RAshid
Applicationofstack by Ali F.RAshid
ali rashid
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
Dipayan Sarkar
 
Stack
StackStack
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
Zidny Nafan
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 

Similar to Data Structures and Agorithm: DS 08 Infix to Postfix.pptx (20)

Stack
StackStack
Stack
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Expression evaluation
Expression evaluationExpression evaluation
Expression evaluation
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Stack
StackStack
Stack
 
Data structures
Data structures Data structures
Data structures
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
week-18x
week-18xweek-18x
week-18x
 
week-17x
week-17xweek-17x
week-17x
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Applicationofstack by Ali F.RAshid
Applicationofstack  by Ali F.RAshid Applicationofstack  by Ali F.RAshid
Applicationofstack by Ali F.RAshid
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
 
Stack
StackStack
Stack
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
 
Object Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptxObject Oriented Programming using C++: Ch09 Inheritance.pptx
Object Oriented Programming using C++: Ch09 Inheritance.pptx
 

Recently uploaded

Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
shahdabdulbaset
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 

Recently uploaded (20)

Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 

Data Structures and Agorithm: DS 08 Infix to Postfix.pptx

  • 1. Data Structure Lecture No. 8 Infix to Postfix Conversion Engr. Rashid Farid Chishti http://youtube.com/rfchishti http://sites.google.com/site/chishti International Islamic University H-10, Islamabad, Pakistan Video Lecture
  • 2.  Consider the infix expressions A+B*C and (A+B)*C.  The postfix versions are ABC*+ and AB+C*.  The order of operands in postfix is the same as the infix.  In scanning from left to right  The operand ‘A’ can be inserted into postfix expression.  The ‘+’ cannot be inserted until its second operand has been scanned and inserted.  The ‘+’ has to be stored away until its proper position is found.  When ‘B’ is seen, it is immediately inserted into the postfix expression.  Can the ‘+’ be inserted now? In the case of A+B*C cannot because * has precedence.  In case of (A+B)*C, the closing parenthesis indicates that ‘+’ must be performed first. Converting Infix to Postfix
  • 3.  So we set priority to each operator. Operator Priority ^ 3(highest) /, * 2 +, - 1 (lowest)  Here is the algorithm that converts infix expression to its postfix form.  The infix expression is without parenthesis. Converting Infix to Postfix 1. Stack s; 2. while( not end of input ) { 3. c = next input character; 4. if( c is an operand ) 5. add c to postfix string; 6. else { 7. while(!s.empty() && pr(c)<= pr(s.top()) 8. { 9. op = s.pop(); 10. add op to the postfix string; 11. } 12. s.push( c ); 13. } 14. while( !s.empty() ) { 15. op = s.pop(); 16. add op to postfix string; 17. }
  • 4.  Example: A + B * C Symb postfix stack A A + A + B AB + * AB + * C ABC + * ABC * + ABC * + Infix to Postfix Example  Read all the symbols one by one from left to right in the given Infix Expression.  If the reading symbol is operand, then directly print it to the result (Output).  If the reading symbol is left parenthesis '(', then Push it on to the Stack.  If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left parenthesis is poped and print each poped symbol to the result.  If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first pop the operators which are already on the stack that have higher or equal precedence than current operator and print them to the result.
  • 5.  Example: A ^ B * C - D + E / F Infix to Postfix Example Symbol Stack Postfix Comments A A A is operand ^ ^ A ^ is operator B ^ A B B is operand * A B ^ (* <= ^) = true, pop ^ * A B ^ stack is empty so push * C * A B ^ C C is operand – A B ^ C * (- <= *) = true, pop * – A B ^ C * stack is empty so push – D – A B ^ C * D D is operand + A B ^ C * D – (+ <= -) = true, pop – + A B ^ C * D – stack is empty so push +
  • 6.  Example: A ^ B * - D + E / F Infix to Postfix Example Symbol Stack Postfix Comments E + A B ^ C * D – E E is operand / + / A B ^ C * D – E (/ <= +) = false, push / F + / A B ^ C * D – E F F is operand + A B ^ C * D – E F / pop / A B ^ C * D – E F / + pop +
  • 7. #include <iostream> #include <string.h> using namespace std; typedef int Type; struct Node{ Type data ; Node * next ; }; class Stack{ private : Node* head; public : Stack( ); bool Is_Empty(); Type Top(); void Push ( Type Data ); Type Pop ( ); ~Stack( ) ; }; Stack::Stack( ){ head = NULL; } 7 Example 1: Infix to Postfix bool Stack::Is_Empty() { return head == NULL; } Type Stack::Top() { if ( !Is_Empty() ) return head->data; return -1; } void Stack :: Push ( Type Data ) { Node *newNode ; newNode = new Node ; if ( newNode == NULL ){ cout << endl << "Stack is full" ; return; } newNode -> data = Data ; newNode -> next = head ; head = newNode ; } 1 2
  • 8. Type Stack :: Pop( ) { if ( Is_Empty() ){ cout << "Stack is empty " ; return -1 ; } Node *current ; Type Data ; current = head ; Data = current -> data ; head = head -> next ; delete current ; return Data ; } Stack :: ~Stack( ){ Node *current ; while ( head != NULL ){ current = head ; head = head -> next ; delete head ; 8 Example 1: Infix to Postfix } } class In2Post{ private: Stack s; char* expr; public: In2Post(char eq[]); bool Is_Operand(char op); int Priority (char op); void Convert(); }; In2Post::In2Post(char eq[]) { expr = new char[strlen(eq) + 1]; strcpy(expr,eq); } 3 4
  • 9. bool In2Post::Is_Operand(char op){ switch(op){ case '+': return false; case '-': return false; case '*': return false; case '/': return false; case '^': return false; default: return true; } } int In2Post::Priority (char op){ switch(op){ case '^': return 3; case '*': case '/': return 2 ; case '+': case '-': return 1 ; default : return 0; } } 9 Example 1: Infix to Postfix void In2Post::Convert(){ char c, p; for ( int i =0 ; expr[i] ; i++){ c = expr[i]; if ( c == ' ' || c == 't' ) continue ; if ( Is_Operand(c)) cout << c <<" "; else{ while( !s.Is_Empty() && (Priority(c) <= Priority(s.Top())) ) { p = s.Pop(); cout << p << " "; } s.Push( c ); } } 5 6
  • 10. while( !s.Is_Empty() ) { c = s.Pop(); cout << c <<" "; } } int main( ){ char expression [] = // {"A+B*C"}; // A B C * + // {"A+B-C"}; // A B + C - {"A ^ B * C - D + E / F"}; // A B ^ C * D – E F / + In2Post I2P(expression); I2P.Convert(); cout << endl; system("PAUSE"); return 0; } 10 Example 1: Infix to Postfix 7 8
  • 11.  Example: A + ( B * C - ( D / E ^ F ) * G ) * H Infix to Postfix Example with Parenthesis Symbol Stack Postfix Comments A A A is operand + + A Stack is empty, push + ( + ( A Push ( B + ( A B B is operand * + ( * A B ( * <= ( ) = false, push * C + ( * A B C C is operand – + ( A B C * ( - <= * ) = true, pop * + ( – A B C * ( - <= ( ) = false, push – ( + ( – ( A B C * push ( D + ( – ( A B C * D D is operand / + ( – ( / A B C * D ( / <= ( ) = false, push / E + ( – ( / A B C * D E E is operand ^ + ( – ( / ^ A B C * D E ( ^ <= / ) = false, push ^
  • 12.  Example: A + ( B * C - ( D / E ^ F ) * G ) * H Infix to Postfix Example with Parenthesis Symbol Stack Postfix Comments F + ( – ( / ^ A B C * D E F F is operand ) + ( – ( / A B C * D E F ^ pop until we get ( + ( – ( A B C * D E F ^ / pop until we get ( + ( – A B C * D E F ^ / pop until we get ( * + ( – * A B C * D E F ^ / ( * <= - ) = false, push * G + ( – * A B C * D E F ^ / G G is operand ) + ( – A B C * D E F ^ / G * pop until we get ( + ( A B C * D E F ^ / G * - pop until we get ( + A B C * D E F ^ / G * - pop until we get ( * + * A B C * D E F ^ / G * - ( * <= + ) = false, push * H + * A B C * D E F ^ / G * - H H is operand + A B C * D E F ^ / G * - H * pop until stack is empty A B C * D E F ^ / G * - H * + pop until stack is empty
  • 13. #include <iostream> #include <math.h> // for pow( , ) using namespace std; typedef char Type; class Stack{ private : struct node{ Type data ; node * next ; } *head; public : Stack( ) { head = NULL ; } Type top() { return head->data; } bool IsEmpty(); void Push ( Type Data ); Type Pop ( ); ~Stack( ) ; }; 13 Example 2: Infix to Postfix with Parenthesis bool Stack::IsEmpty(){ return head ==NULL; } void Stack :: Push ( Type Data ) { node *newNode ; newNode = new node ; if ( newNode == NULL ){ cout << endl << "Stack is full" ; return; } newNode -> data = Data ; newNode -> next = head ; head = newNode ; } 1 2
  • 14. Type Stack :: Pop( ) { if ( IsEmpty() ){ cout << "Stack is empty " ; return -1 ; } node *current ; Type Data ; current = head ; Data = current -> data ; head = head -> next ; delete current ; return Data ; } // deallocates memory Stack :: ~Stack( ){ node *current ; while ( head != NULL ){ current = head ; head = head -> next ; 14 Example 2: Infix to Postfix with Parenthesis delete head ; } } class In2Post { private: Stack s; char* expr; public: In2Post(char eq[]); bool is_operand(char op); int Priority (char op); void Convert(); }; In2Post::In2Post(char eq[]) { expr = new char[strlen(eq) + 1]; strcpy(expr,eq); } 3 4
  • 15. bool In2Post :: is_operand(char op){ switch(op){ case '+': return false; case '-': return false; case '*': return false; case '/': return false; case '^': return false; case '(': return false; case ')': return false; default : return true ; } } 15 Example 2: Infix to Postfix with Parenthesis int In2Post::Priority (char op){ switch(op){ case '^': return 3; case '*': case '/': return 2 ; case '+': case '-': return 1 ; default : return 0; } } 5 6
  • 16. void In2Post::Convert(){ char c, p; for ( int i =0 ; expr[i] ; i++){ c = expr[i]; if ( c == ' ' || c == 't' ) continue ; else if ( is_operand(c)) cout << c <<" "; else if(c=='(' ) s.Push( c ); else if(c==')' ){ while( true ){ p = s.Pop(); if( p == '(') break; else cout << p <<" "; } } 16 Example 2: Infix to Postfix with Parenthesis else{ while( !s.IsEmpty() && (Priority(c) <= Priority(s.top()))) { p = s.Pop(); if( p !=')' && p !='(') cout << p << " "; } s.Push( c ); } } while( !s.IsEmpty() ) { p = s.Pop(); if( p !=')' && p !='(') cout << p << " "; } } 7 8
  • 17. int main( ){ char expression [] = // {"A+B*C"}; // ABC*+ // {"A+B-C"}; // AB+C- // {"A^B*C-D+E/F"}; // = A B ^ C*D – E F/+ // {"(A+B)*(C-D)"}; // = A B + C D - * // {"(A+B)*C"}; // ABC*+ {" A + ( B * C - ( D / E ^ F )" " * G ) * H "}; // = A B C * D E F ^ / G * - H * + In2Post I2P(expression); I2P.Convert(); cout << endl; system("PAUSE"); return 0; } 17 Example 2: Infix to Postfix with Parenthesis 9 10