Stacks
Lecture-08
Kiran Ijaz
Stacks
“A Stack is a special kind of list in which all
insertions and deletions take place at one
end, called the Top”
Other Names
 Pushdown List
 Last In First Out (LIFO)
Stacks
Examples:
 Books on a floor
 Dishes on a shelf
Common Operations on Stacks
1. MAKENULL(S): Make Stack S be an empty
stack.
2. TOP(S): Return the element at the top of stack S.
3. POP(S): Remove the top element of the stack.
4. PUSH(S): Insert the element x at the top of the
stack.
5. EMPTY(S): Return true if S is an empty stack;
return false otherwise.
Static and Dynamic Stacks
 There are two kinds of stack data structure -
a) static, i.e. they have a fixed size, and are
implemented as arrays.
b) dynamic, i.e. they grow in size as needed,
and implemented as linked lists
Push and Pop operations of
Stack
An Array Implementation of Stacks
First Implementation
 Elements are stored in contiguous cells of an array.
 New elements can be inserted to the top of the list.
Last Element
Second Element
First Element
List
Empty
maxlength
top
An Array Implementation of Stacks
Problem with this implementation
 Every PUSH and POP requires moving the entire array
up and down.
1
1
2
1
2
3
1
2
Since, in a stack the insertion and deletion take
place only at the top, so…
A better Implementation:
 Anchor the bottom of the stack at the bottom of the array
 Let the stack grow towards the top of the array
 Top indicates the current position of the first stack element.
An Array Implementation of Stacks
A better Implementation:
First Element
Last Element
maxlength
top
Second Element
1
2
.
.
An Array Implementation of Stacks
A Stack Class
#ifndef INTSTACK_H
#define INTSTACK_H
class IntStack
{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int);
void push(int);
void pop(int &);
bool isFull(void);
bool isEmpty(void);
};
#endif
Implementation
//*******************
// Constructor *
//*******************
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
Push
// Member function push pushes the argument onto *
// the stack. *
void IntStack::push(int num)
{
if (isFull())
cout << "The stack is full.n";
else
{
top++;
stackArray[top] = num;
}
}
// Member function pop pops the value at the top
// of the stack off, and copies it into the variable
// passed as an argument.
void IntStack::pop(int &num)
{
if (isEmpty())
cout << "The stack is empty.n";
else
{
num = stackArray[top];
top--;
}
}
//***************************************************
// Member function isFull returns true if the stack *
// is full, or false otherwise. *
//***************************************************
bool IntStack::isFull(void)
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
//**********************************************
// Member funciton isEmpty returns true if the
//stack *
// is empty, or false otherwise.*
//***********************************************
bool IntStack::isEmpty(void)
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
// This program demonstrates the IntStack class.
#include <iostream.h>
#include "intstack.h“
void main(void)
{
IntStack stack(5);
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
cout << "Pushing 20n";
stack.push(20);
cout << "Pushing 25n";
stack.push(25);
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
}
Program Output
Pushing 5
Pushing 10
Pushing 15
Pushing 20
Pushing 25
Popping...
25
20
15
10
5
About Program 1
• In the program, the constructor is called
with the argument 5. This sets up the
member variables as shown in Figure 1.
Since top is set to –1, the stack is empty
• Figure 3 shows the state of the member
variables after all five calls to the push
function. Now the top of the stack is at
element 4, and the stack is full.
Notice that the pop function uses a reference
parameter, num.
The value that is popped off the stack is copied into
num so it can be used later in the program.
Figure 4 (on the next slide) depicts the state of
the class members, and the num parameter, just
after the first value is popped off the stack.
Implementing other Stack Operations
More complex operations can be built on the basic stack class we
have just described, e.g. a class called MathStack.
MathStack has 2 member functions :- add( ) sub( )
Stack Templates
The stack class so far work with integers
only. A stack template can be used to
work with any data type.
A Linked-List Implementation of
Stacks
 Stack can expand or shrink with each PUSH or
POP operation.
 PUSH and POP operate only on the header cell
and the first cell on the list.
x y .
z
Top
Linked List Implementation of Stack
class Stack
{
struct node
{
int data;
node *next;
}*top;
public:
void Push(int newelement);
int Pop(void);
bool IsEmpty();
};
void Stack::Push(int newelement)
{
node *newptr;
newptr=new node;
newptr->data=newelement;
newptr->next=top;
top=newptr;
}
int Stack:Pop(void)
{
if (IsEmpty()) { cout<<“underflow error”; return;}
tempptr=top;
int returnvalue=top->data;
top=top->next;
delete tempptr;
return returnvalue;
}
void Stack::IsEmpty()
{
if (top==NULL) return true;
else return false;
}
Program 3
// This program demonstrates the dynamic stack
// class DynIntClass.
#include <iostream.h>
#include "dynintstack.h“
void main(void)
{
DynIntStack stack;
int catchVar;
cout << "Pushing 5n";
stack.push(5);
cout << "Pushing 10n";
stack.push(10);
cout << "Pushing 15n";
stack.push(15);
cout << "Popping...n";
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
stack.pop(catchVar);
cout << catchVar << endl;
cout << "nAttempting to pop again... ";
stack.pop(catchVar);
}
Program Output
Pushing 5
Pushing 10
Pushing 15
Popping...
15
10
5
Attempting to pop again... The stack is empty.
Application of Stack
Data Structures using C
and C++, Section 2.3
INFIX, POSTFIX and PREFIX
 Infix: A+B-C
 Postfix: AB+C-
 Prefix: -+ABC
Order of Precedence of Operators
 Exponentiation
 Multiplication/Division
 Addition/Subtraction
Infix: ( (A+B)*C-(D-E) ) $ (F+G)
Conversion to Postfix Expression
 ( (AB+)*C-(DE-) ) $ (FG+)
( (AB+C*)-(DE-) ) $ (FG+)
(AB+C*DE--) $ (FG+)
AB+C*DE- -FG+$
Exercise: Convert the following to Postfix
( A + B ) * ( C – D)
A $ B * C – D + E / F / (G + H)
Conversion to Prefix Expression
The precedence rules for converting an expression from infix to
prefix are identical. The only change from postfix is that the
operator is placed before the operands rather than after them.
Evaluating a Postfix Expression
Each operator in a postfix string refers to the previous two
operands in the string.
Algorithm to Evaluate a Postfix
Expression
opndstk = the empty stack
//scan the input string reading one
element
//at a time into symb
while (not end of input) {
symb = next input character;
if (symb is an operand)
push(opndstk, symb)
else {
/* symb is an operator */
opnd2 = pop(opndstk);
opnd1 = pop(opndstk);
value = result of applying symb to
opnd1 and opnd2;
push(opndstk, value);
} /* end else */
} /* end while */
return (pop(opndstk));
Example:
Postfix Expression: 6 2 3 + - 3 8 2 / + * 2 $ 3 +
sym
b
opnd
1
opnd2 valu
e
opndstk
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
$ 7 2 49 49
3 7 2 49 49,3
+ 49 3 52 52
Conversion of Infix Expression to
postfix
A+B*C = ABC*+
(A+B)*C = AB+C*
There must be a precedence function.
prcd(op1, op2), where op1 and op2 are characters representing operators.
This function returns TRUE if op1 has precendence over op2 when op1
appears to the left of op2 in an infix expression without parenthesis.
prcd(op1,op2) returns FALSE otherwise.
For example prcd(‘*’,’+’) and prcd(‘+’,’+’) are TRUE whereas prcd(‘+’,’*’) is
FALSE.
prcd(‘$’,’$’) = FALSE
prcd( ‘(‘ , op) = FALSE for any operator op
prcd( op, ‘(‘ ) = FALSE for any operator op other than ‘)’
prcd( op, ‘)‘ ) = TRUE for any operator op other than ‘(‘
prcd( ‘)‘ ,op ) = undefined for any operator op (an error)
Algorithm to Convert Infix to Postfix
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand)
add symb to the postfix string
else {
while (!empty(opstk) &&
prcd(stacktop(opstk),symb) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
push(opstk, symb);
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Example-1: A+B*C
sym
b
Postfix
string
opstk
A A
+ A +
B AB +
* AB + *
C ABC + *
ABC* +
ABC*+
Algorithm to Convert Infix to Postfix
Example-2: (A+B)*C
symb Postfix
string
opstk
( (
A A (
+ A ( +
B AB ( +
) AB+
* AB+ *
C AB+C *
AB+C*
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand)
add symb to the postfix string
else {
while (!empty(opstk) &&
prcd(stacktop(opstk),symb) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
push(opstk, symb);
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Algorithm to Convert Infix to Postfix
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand)
add symb to the postfix string
else {
while (!empty(opstk) &&
prcd(stacktop(opstk),symb) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
push(opstk, symb);
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Example-3: ( (A-(B+C) ) *D ) $ (E+F)
Algorithm to Convert Infix to Postfix
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand)
add symb to the postfix string
else {
while (!empty(opstk) &&
prcd(stacktop(opstk),symb) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
push(opstk, symb);
} /* end else */
} /* end while */
/* output any remaining operators */
while (!empty(opstk) ) {
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
Example-3: ( (A-(B+C) ) *D ) $ (E+F)
symb Postfix string opstk
( (
( ((
A A ((
- A ((-
( A ((-(
B AB ((-(
+ AB ((-(+
C ABC ((-(+
) ABC+ ((-
) ABC+- (
* ABC+- (*
D ABC+-D (*
) ABC+-D*
$ ABC+-D* $
( ABC+-D* $(
E ABC+-D*E $(
+ ABC+-D*E $(+
F ABC+-D*EF $(+
) ABC+-D*EF+ $
ABC+-D*EF+$

More Related Content

PDF
Data structures stacks
PPTX
Data Structure and Algorithms by Sabeen Memon03.pptx
PPTX
Unit 3 Stacks and Queues.pptx
PDF
PPTX
Data structures
PPT
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
PPT
Stacks.ppt
PPT
Stacks.ppt
Data structures stacks
Data Structure and Algorithms by Sabeen Memon03.pptx
Unit 3 Stacks and Queues.pptx
Data structures
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stacks.ppt
Stacks.ppt

Similar to Lec-7 Stacks FOR BSCS STUDENTS STACK EXPLANATION (20)

PPTX
Stack.pptx
PPT
Stacks
PPTX
Stack data structure
PPTX
Stacks and queues using aaray line .pptx
PPTX
Lec5-Stack-bukc-28022024-112316am (1) .pptx
PPT
week 7,8,10,11 alll files included from .ppt
PPSX
PPT
12650891 (1).ppthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
PPTX
Chapter 5-stack.pptx
PPT
Algo>Stacks
PPT
01 stack 20160908_jintaek_seo
PPTX
Unit 3 stack
PPTX
Stacks in c++
PPTX
Stack_Overview_Implementation_WithVode.pptx
PPTX
Stack Data Structure Explained with Array and Linked List Implementation, Ope...
PDF
Data Structures And Algorithms(stacks queues)
PPTX
Introduction to information about Data Structure.pptx
PPT
Lec 4 Stack of Data Structures & Algorithms
PDF
Stacks,queues,linked-list
PPTX
Stack - Data Structure - Notes
Stack.pptx
Stacks
Stack data structure
Stacks and queues using aaray line .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
week 7,8,10,11 alll files included from .ppt
12650891 (1).ppthhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
Chapter 5-stack.pptx
Algo>Stacks
01 stack 20160908_jintaek_seo
Unit 3 stack
Stacks in c++
Stack_Overview_Implementation_WithVode.pptx
Stack Data Structure Explained with Array and Linked List Implementation, Ope...
Data Structures And Algorithms(stacks queues)
Introduction to information about Data Structure.pptx
Lec 4 Stack of Data Structures & Algorithms
Stacks,queues,linked-list
Stack - Data Structure - Notes
Ad

More from MuddassarAli6 (7)

PPT
Lec-6 List ADT & Linked Lists FOR BSCS STUDENTS
PPT
Lec-3 Time Complexity OR THW STUDENTS OF
PPT
Lec-4 Abstract Data Type FOR THW STUDENTS OF
PPT
Lec-4 Abstract Data Type FOR THE STUDENTS OF BSCS
PPT
DSA Lec-3 Time Complexity FOR THE STUDENTS OF BSCS
PPT
DSA Lec-2 Arrays ADT FOR THE STUDENTS OF BSCS
PPT
dsa Lec-1 Introduction FOR THE STUDENTS OF bscs
Lec-6 List ADT & Linked Lists FOR BSCS STUDENTS
Lec-3 Time Complexity OR THW STUDENTS OF
Lec-4 Abstract Data Type FOR THW STUDENTS OF
Lec-4 Abstract Data Type FOR THE STUDENTS OF BSCS
DSA Lec-3 Time Complexity FOR THE STUDENTS OF BSCS
DSA Lec-2 Arrays ADT FOR THE STUDENTS OF BSCS
dsa Lec-1 Introduction FOR THE STUDENTS OF bscs
Ad

Recently uploaded (20)

PPTX
DATA ANALYTICS COURSE IN PITAMPURA.pptx
PPTX
Chapter security of computer_8_v8.1.pptx
PPTX
lung disease detection using transfer learning approach.pptx
PDF
Concepts of Database Management, 10th Edition by Lisa Friedrichsen Test Bank.pdf
PPTX
9 Bioterrorism.pptxnsbhsjdgdhdvkdbebrkndbd
PDF
Delhi c@ll girl# cute girls in delhi with travel girls in delhi call now
PPTX
PPT for Diseases (1)-2, types of diseases.pptx
PDF
technical specifications solar ear 2025.
PDF
Grey Minimalist Professional Project Presentation (1).pdf
PDF
Mcdonald's : a half century growth . pdf
PPT
What is life? We never know the answer exactly
PPTX
ch20 Database System Architecture by Rizvee
PPT
Technicalities in writing workshops indigenous language
PPTX
Stats annual compiled ipd opd ot br 2024
PPTX
Basic Statistical Analysis for experimental data.pptx
PPTX
inbound2857676998455010149.pptxmmmmmmmmm
PDF
Hikvision-IR-PPT---EN.pdfSADASDASSAAAAAAAAAAAAAAA
PDF
REPORT CARD OF GRADE 2 2025-2026 MATATAG
PPTX
PPT for Diseases.pptx, there are 3 types of diseases
PPTX
Statisticsccdxghbbnhhbvvvvvvvvvv. Dxcvvvhhbdzvbsdvvbbvv ccc
DATA ANALYTICS COURSE IN PITAMPURA.pptx
Chapter security of computer_8_v8.1.pptx
lung disease detection using transfer learning approach.pptx
Concepts of Database Management, 10th Edition by Lisa Friedrichsen Test Bank.pdf
9 Bioterrorism.pptxnsbhsjdgdhdvkdbebrkndbd
Delhi c@ll girl# cute girls in delhi with travel girls in delhi call now
PPT for Diseases (1)-2, types of diseases.pptx
technical specifications solar ear 2025.
Grey Minimalist Professional Project Presentation (1).pdf
Mcdonald's : a half century growth . pdf
What is life? We never know the answer exactly
ch20 Database System Architecture by Rizvee
Technicalities in writing workshops indigenous language
Stats annual compiled ipd opd ot br 2024
Basic Statistical Analysis for experimental data.pptx
inbound2857676998455010149.pptxmmmmmmmmm
Hikvision-IR-PPT---EN.pdfSADASDASSAAAAAAAAAAAAAAA
REPORT CARD OF GRADE 2 2025-2026 MATATAG
PPT for Diseases.pptx, there are 3 types of diseases
Statisticsccdxghbbnhhbvvvvvvvvvv. Dxcvvvhhbdzvbsdvvbbvv ccc

Lec-7 Stacks FOR BSCS STUDENTS STACK EXPLANATION

  • 2. Stacks “A Stack is a special kind of list in which all insertions and deletions take place at one end, called the Top” Other Names  Pushdown List  Last In First Out (LIFO)
  • 3. Stacks Examples:  Books on a floor  Dishes on a shelf
  • 4. Common Operations on Stacks 1. MAKENULL(S): Make Stack S be an empty stack. 2. TOP(S): Return the element at the top of stack S. 3. POP(S): Remove the top element of the stack. 4. PUSH(S): Insert the element x at the top of the stack. 5. EMPTY(S): Return true if S is an empty stack; return false otherwise.
  • 5. Static and Dynamic Stacks  There are two kinds of stack data structure - a) static, i.e. they have a fixed size, and are implemented as arrays. b) dynamic, i.e. they grow in size as needed, and implemented as linked lists
  • 6. Push and Pop operations of Stack
  • 7. An Array Implementation of Stacks First Implementation  Elements are stored in contiguous cells of an array.  New elements can be inserted to the top of the list. Last Element Second Element First Element List Empty maxlength top
  • 8. An Array Implementation of Stacks Problem with this implementation  Every PUSH and POP requires moving the entire array up and down. 1 1 2 1 2 3 1 2
  • 9. Since, in a stack the insertion and deletion take place only at the top, so… A better Implementation:  Anchor the bottom of the stack at the bottom of the array  Let the stack grow towards the top of the array  Top indicates the current position of the first stack element. An Array Implementation of Stacks
  • 10. A better Implementation: First Element Last Element maxlength top Second Element 1 2 . . An Array Implementation of Stacks
  • 11. A Stack Class #ifndef INTSTACK_H #define INTSTACK_H class IntStack { private: int *stackArray; int stackSize; int top; public: IntStack(int); void push(int); void pop(int &); bool isFull(void); bool isEmpty(void); }; #endif
  • 12. Implementation //******************* // Constructor * //******************* IntStack::IntStack(int size) { stackArray = new int[size]; stackSize = size; top = -1; }
  • 13. Push // Member function push pushes the argument onto * // the stack. * void IntStack::push(int num) { if (isFull()) cout << "The stack is full.n"; else { top++; stackArray[top] = num; } }
  • 14. // Member function pop pops the value at the top // of the stack off, and copies it into the variable // passed as an argument. void IntStack::pop(int &num) { if (isEmpty()) cout << "The stack is empty.n"; else { num = stackArray[top]; top--; } }
  • 15. //*************************************************** // Member function isFull returns true if the stack * // is full, or false otherwise. * //*************************************************** bool IntStack::isFull(void) { bool status; if (top == stackSize - 1) status = true; else status = false; return status; }
  • 16. //********************************************** // Member funciton isEmpty returns true if the //stack * // is empty, or false otherwise.* //*********************************************** bool IntStack::isEmpty(void) { bool status; if (top == -1) status = true; else status = false; return status; }
  • 17. // This program demonstrates the IntStack class. #include <iostream.h> #include "intstack.h“ void main(void) { IntStack stack(5); int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15); cout << "Pushing 20n"; stack.push(20); cout << "Pushing 25n"; stack.push(25);
  • 18. cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; }
  • 19. Program Output Pushing 5 Pushing 10 Pushing 15 Pushing 20 Pushing 25 Popping... 25 20 15 10 5
  • 20. About Program 1 • In the program, the constructor is called with the argument 5. This sets up the member variables as shown in Figure 1. Since top is set to –1, the stack is empty
  • 21. • Figure 3 shows the state of the member variables after all five calls to the push function. Now the top of the stack is at element 4, and the stack is full.
  • 22. Notice that the pop function uses a reference parameter, num. The value that is popped off the stack is copied into num so it can be used later in the program. Figure 4 (on the next slide) depicts the state of the class members, and the num parameter, just after the first value is popped off the stack.
  • 23. Implementing other Stack Operations More complex operations can be built on the basic stack class we have just described, e.g. a class called MathStack. MathStack has 2 member functions :- add( ) sub( )
  • 24. Stack Templates The stack class so far work with integers only. A stack template can be used to work with any data type.
  • 25. A Linked-List Implementation of Stacks  Stack can expand or shrink with each PUSH or POP operation.  PUSH and POP operate only on the header cell and the first cell on the list. x y . z Top
  • 26. Linked List Implementation of Stack class Stack { struct node { int data; node *next; }*top; public: void Push(int newelement); int Pop(void); bool IsEmpty(); };
  • 27. void Stack::Push(int newelement) { node *newptr; newptr=new node; newptr->data=newelement; newptr->next=top; top=newptr; } int Stack:Pop(void) { if (IsEmpty()) { cout<<“underflow error”; return;} tempptr=top; int returnvalue=top->data; top=top->next; delete tempptr; return returnvalue; }
  • 28. void Stack::IsEmpty() { if (top==NULL) return true; else return false; }
  • 29. Program 3 // This program demonstrates the dynamic stack // class DynIntClass. #include <iostream.h> #include "dynintstack.h“ void main(void) { DynIntStack stack; int catchVar; cout << "Pushing 5n"; stack.push(5); cout << "Pushing 10n"; stack.push(10); cout << "Pushing 15n"; stack.push(15);
  • 30. cout << "Popping...n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; cout << "nAttempting to pop again... "; stack.pop(catchVar); } Program Output Pushing 5 Pushing 10 Pushing 15 Popping... 15 10 5 Attempting to pop again... The stack is empty.
  • 31. Application of Stack Data Structures using C and C++, Section 2.3
  • 32. INFIX, POSTFIX and PREFIX  Infix: A+B-C  Postfix: AB+C-  Prefix: -+ABC Order of Precedence of Operators  Exponentiation  Multiplication/Division  Addition/Subtraction
  • 33. Infix: ( (A+B)*C-(D-E) ) $ (F+G) Conversion to Postfix Expression  ( (AB+)*C-(DE-) ) $ (FG+) ( (AB+C*)-(DE-) ) $ (FG+) (AB+C*DE--) $ (FG+) AB+C*DE- -FG+$ Exercise: Convert the following to Postfix ( A + B ) * ( C – D) A $ B * C – D + E / F / (G + H)
  • 34. Conversion to Prefix Expression The precedence rules for converting an expression from infix to prefix are identical. The only change from postfix is that the operator is placed before the operands rather than after them. Evaluating a Postfix Expression Each operator in a postfix string refers to the previous two operands in the string.
  • 35. Algorithm to Evaluate a Postfix Expression opndstk = the empty stack //scan the input string reading one element //at a time into symb while (not end of input) { symb = next input character; if (symb is an operand) push(opndstk, symb) else { /* symb is an operator */ opnd2 = pop(opndstk); opnd1 = pop(opndstk); value = result of applying symb to opnd1 and opnd2; push(opndstk, value); } /* end else */ } /* end while */ return (pop(opndstk)); Example: Postfix Expression: 6 2 3 + - 3 8 2 / + * 2 $ 3 + sym b opnd 1 opnd2 valu e opndstk 6 6 2 6,2 3 6,2,3 + 2 3 5 6,5 - 6 5 1 1 3 6 5 1 1,3 8 6 5 1 1,3,8 2 6 5 1 1,3,8,2 / 8 2 4 1,3,4 + 3 4 7 1,7 * 1 7 7 7 2 1 7 7 7,2 $ 7 2 49 49 3 7 2 49 49,3 + 49 3 52 52
  • 36. Conversion of Infix Expression to postfix A+B*C = ABC*+ (A+B)*C = AB+C* There must be a precedence function. prcd(op1, op2), where op1 and op2 are characters representing operators. This function returns TRUE if op1 has precendence over op2 when op1 appears to the left of op2 in an infix expression without parenthesis. prcd(op1,op2) returns FALSE otherwise. For example prcd(‘*’,’+’) and prcd(‘+’,’+’) are TRUE whereas prcd(‘+’,’*’) is FALSE. prcd(‘$’,’$’) = FALSE prcd( ‘(‘ , op) = FALSE for any operator op prcd( op, ‘(‘ ) = FALSE for any operator op other than ‘)’ prcd( op, ‘)‘ ) = TRUE for any operator op other than ‘(‘ prcd( ‘)‘ ,op ) = undefined for any operator op (an error)
  • 37. Algorithm to Convert Infix to Postfix opstk = the empty stack; while (not end of input) { symb = next input character; if (symb is an operand) add symb to the postfix string else { while (!empty(opstk) && prcd(stacktop(opstk),symb) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ push(opstk, symb); } /* end else */ } /* end while */ /* output any remaining operators */ while (!empty(opstk) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ Example-1: A+B*C sym b Postfix string opstk A A + A + B AB + * AB + * C ABC + * ABC* + ABC*+
  • 38. Algorithm to Convert Infix to Postfix Example-2: (A+B)*C symb Postfix string opstk ( ( A A ( + A ( + B AB ( + ) AB+ * AB+ * C AB+C * AB+C* opstk = the empty stack; while (not end of input) { symb = next input character; if (symb is an operand) add symb to the postfix string else { while (!empty(opstk) && prcd(stacktop(opstk),symb) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ push(opstk, symb); } /* end else */ } /* end while */ /* output any remaining operators */ while (!empty(opstk) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */
  • 39. Algorithm to Convert Infix to Postfix opstk = the empty stack; while (not end of input) { symb = next input character; if (symb is an operand) add symb to the postfix string else { while (!empty(opstk) && prcd(stacktop(opstk),symb) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ push(opstk, symb); } /* end else */ } /* end while */ /* output any remaining operators */ while (!empty(opstk) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ Example-3: ( (A-(B+C) ) *D ) $ (E+F)
  • 40. Algorithm to Convert Infix to Postfix opstk = the empty stack; while (not end of input) { symb = next input character; if (symb is an operand) add symb to the postfix string else { while (!empty(opstk) && prcd(stacktop(opstk),symb) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ push(opstk, symb); } /* end else */ } /* end while */ /* output any remaining operators */ while (!empty(opstk) ) { topsymb = pop(opstk); add topsymb to the postfix string; } /* end while */ Example-3: ( (A-(B+C) ) *D ) $ (E+F) symb Postfix string opstk ( ( ( (( A A (( - A ((- ( A ((-( B AB ((-( + AB ((-(+ C ABC ((-(+ ) ABC+ ((- ) ABC+- ( * ABC+- (* D ABC+-D (* ) ABC+-D* $ ABC+-D* $ ( ABC+-D* $( E ABC+-D*E $( + ABC+-D*E $(+ F ABC+-D*EF $(+ ) ABC+-D*EF+ $ ABC+-D*EF+$

Editor's Notes

  • #2: But NO constraints on HOW the problem is solved