0% found this document useful (0 votes)
49 views

Data Structures: Stacks Lecture 5,6

The document discusses stacks and their application in validating mathematical expressions with nested parentheses. It describes how a stack can be used to keep track of opening and closing parentheses in an expression to ensure they are properly balanced. Expressions with multiple delimiter types like parentheses, brackets and braces can also be validated using a stack that tracks the delimiter types. Pseudocode is provided that uses a stack to parse an expression string and return whether it has a valid matching of parentheses. The document also covers infix, postfix and prefix notation for expressions and how converting expressions to postfix form makes them easier to evaluate by eliminating the need for operator precedence rules.

Uploaded by

Saadia Mobeen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Data Structures: Stacks Lecture 5,6

The document discusses stacks and their application in validating mathematical expressions with nested parentheses. It describes how a stack can be used to keep track of opening and closing parentheses in an expression to ensure they are properly balanced. Expressions with multiple delimiter types like parentheses, brackets and braces can also be validated using a stack that tracks the delimiter types. Pseudocode is provided that uses a stack to parse an expression string and return whether it has a valid matching of parentheses. The document also covers infix, postfix and prefix notation for expressions and how converting expressions to postfix form makes them easier to evaluate by eliminating the need for operator precedence rules.

Uploaded by

Saadia Mobeen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

Data Structures

Stacks
Lecture 5,6

FUIEMS Malik Imran Daud


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 right and left parentheses
2. Every right parenthesis is preceded by a matching left
parenthesis

FUIEMS Malik Imran Daud


Expressions
• (A+B) * C Valid
• A + B) Invalid
• (A+B] Invalid

FUIEMS Malik Imran Daud


Rules
• Each left parenthesis is an opening scope
• Each right parenthesis is a closing scope
• The number of left parentheses encountered whose matching
right parentheses have not been encountered is nesting depth
at that point
• Parentheses count = 0 at the end means that no scopes have
been left open and left and right parentheses exactly match
• The parentheses count at any time should never become
negative. IF negative then its error.

FUIEMS Malik Imran Daud


Expressions
• ((A+B)
Error
• 122221

• (A*B)
• 11110 Right

• A*B(
• 0001 Error

FUIEMS Malik Imran Daud


Parsing Parenthesis
• Let us change the problem slightly
• Three different kinds of scope delimiters exist e.g { x
+ (y – [a +b]) }

• The scope ender must be of same type as scope


opener
• It is necessary to keep track of not only the count of
scope but also the types
• A stack may be used to keep track of the types of
scopes encountered

FUIEMS Malik Imran Daud


Stacks in validation expression
• Whenever a scope opener is encountered it is pushed
into the stack
• Whenever a scope ender is encountered the stack is
examined
• If the stack is empty the scope ender does not have a
matching opener and string is invalid
• If stack is not empty we pop an item and check if it
corresponds to scope ender
• If match occurs we continue, at the end of the string
the stack must be empty

FUIEMS Malik Imran Daud


Valid = true
Pusedo-code
S = the empty stack // array of chars say char s[100]
While (we have not read the entire string) {
read the next symbol (symb) of the string;
if (symb == ‘(‘ || symb == ‘[‘ || symb == ‘{‘)
push (s, symb);
if (symb == ‘)‘ || symb == ‘]‘ || symb == ‘}‘)
if (empty(s))
valid = false;
else {
I = pop (s);
if ( I is not the matching opener of symb)
valid = false;
}// end of else
} //end while
If (valid)
cout << “Valid String” << endl;
Else
cout << “not a valid string”

FUIEMS Malik Imran Daud


{ x + (y – [a +b]) }

( ( (

{ { { { {

1 2 3 4 5 6 7
FUIEMS Malik Imran Daud
Another implementation of
Stack
• Stacks can be declared by using structures containing
two objects

#define STACKSIZE 100


struct stack {
int top;
int items[STACKSIZE];
};

struct stack s;

FUIEMS Malik Imran Daud


empty()
If (s.top==-1)
– Stack is empty
Else
stack is not empty

int empty(struct stack *ps)


{
if (ps->top == -1) if (empty(&s))
return(true);
else cout<<“stack is empty”
return(false); else
}
cout<<“stack is not
empty”

FUIEMS Malik Imran Daud


Push()
void push(struct stack *ps, int x)
{
  ps->items[++(ps->top)] = x;
}

int push(struct stack *ps, int x)


{
if (ps->top==STACKSIZE-1)
{
cout<<“stack overflow”;
return(false);
}
  ps->items[++(ps->top)] = x;
return(true);
}
FUIEMS Malik Imran Daud
POP( )
int pop(struct stack *ps)
{
if (empty(ps))
{
cout<<stack underflow;
return(false);
}
 return (ps->items[ps->top--]);
}

To use the pop function, the programmer can declare int x


and write

x=pop(&s);

FUIEMS Malik Imran Daud


(Infix, Postfix and Prefix
Expressions)

FUIEMS Malik Imran Daud


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.

FUIEMS Malik Imran Daud


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.

FUIEMS Malik Imran Daud


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.

FUIEMS Malik Imran Daud


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
– a*b/c/d

FUIEMS Malik Imran Daud


Delimiters
• Subexpression within delimiters is treated as a single
operand, independent from the remainder of the
expression.
– (a + b) * (c – d) / (e – f)

FUIEMS Malik Imran Daud


WHY
• Why to use these weird looking PREFIX and POSTFIX notations
when we have simple INFIX notation?

• 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’ Priority and Associative property
– For example expression 3+5*4 evaluate to 32 i.e. (3+5)*4
or to 23 i.e. 3+(5*4).

• To solve this problem Precedence or Priority of the operators


were defined. Operator precedence governs evaluation order. An
operator with higher precedence is applied before an operator
with lower precedence.

FUIEMS Malik Imran Daud


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.

FUIEMS Malik Imran Daud


Examples of infix to prefix and
post fix
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

FUIEMS Malik Imran Daud


Example: postfix expressions

• Postfix notation is another way of writing arithmetic


expressions.
 

• In postfix notation, the operator is written after the two


 
operands.
infix: 2+5 postfix: 2 5 +
• Expressions are evaluated from left to right.
 
• Precedence rules and parentheses are never needed!!

FUIEMS Malik Imran Daud


Suppose that we would like to
rewrite A+B*C in postfix
• Applying the rules of precedence,we obtained

A+B*C
A+(B*C) Parentheses for emphasis
A+(BC*) Convert the multiplication,Let D=BC*
A+D Convert the addition

A(D)+
ABC*+ Postfix Form

FUIEMS Malik Imran Daud


Postfix Examples
Infix Postfix Evaluation

2-3*4+5 234*-5+ -5

(2 - 3) * (4 + 5) 23-45+* -9

2- (3 * 4 +5) 234*5+- -15

Why ? No brackets necessary !

FUIEMS Malik Imran Daud


Algorithm for Infix
1)  Examine the next element in the input.
to Postfix
2)  If it is operand, output it.
3)  If it is opening parenthesis, push it on stack.
4)  If it is an operator, then
i) If stack is empty, push operator on stack.
ii) If the top of stack is opening parenthesis, push operator on stack
iii) If it has higher priority than the top of stack, push operator on stack.
iv) if top of stack has high priority then pop the operator from the stack and
output it, repeat step 4

5)  If it is a closing parenthesis, pop operators from stack and output them until
an opening parenthesis is encountered. pop and discard the opening
parenthesis.
6)  If there is more input go to step 1
7)  If there is no more input, pop the remaining operators to output.

FUIEMS Malik Imran Daud


Suppose we want to convert 2*3/(2-1)+5*3 into Postfix form,
Expression Stack Output
2 Empty 2
* * 2
3 * 23
/ / 23*
( /( 23*
2 /( 23*2
- /(- 23*2
1 /(- 23*21
) / 23*21-
+ + 23*21-/
5 + 23*21-/5
* +* 23*21-/53
3 +* 23*21-/53
Empty   23*21-/53*+
FUIEMS So,
Malik Imran the Postfix Expression is 23*21-/53*+
Daud
Example
• ( 5 + 6) * 9 +10
will be
• 5 6 + 9 * 10 +

FUIEMS Malik Imran Daud


Evaluating a postfix expression
• Each operator in a postfix string refers to the previous
two operands in the string.
• Suppose that each time we read an operand we push it
into a stack. When we reach an operator, its operands
will then be top two elements on the stack
• We can then pop these two elements, perform the
indicated operation on them, and push the result on the
stack.
• So that it will be available for use as an operand of the
next operator.

FUIEMS Malik Imran Daud


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.

FUIEMS Malik Imran Daud


Evaluating a postfix expression
• Initialise an empty stack
• While token remain in the input stream
– Read next token
– If token is a number, push it into the stack
– Else, if token is an operator, pop top two tokens off the
stack,apply the operator, and push the answer back into the
stack
• Pop the answer off the stack.

FUIEMS Malik Imran Daud


Example: postfix expressions
(cont.)

FUIEMS Malik Imran Daud


Postfix expressions:
Algorithm using stacks (cont.)

FUIEMS Malik Imran Daud


Algorithm for evaluating a
postfix expression (Cond.)
WHILE more input items exist
{
If symb is an operand
then push (opndstk,symb)
else //symbol is an operator
{
Opnd1=pop(opndstk);
Opnd2=pop(opndnstk);
Value = result of applying symb to opnd1 & opnd2
Push(opndstk,value);
} //End of else
} // end while
Result = pop (opndstk);

FUIEMS Malik Imran Daud


Question : Evaluate the
following expression in
postfix :
623+-382/+*2^3+
Final answer is
• 49
• 51
• 52
• 7
• None of these

FUIEMS Malik Imran Daud


Evaluate- 623+-382/+*2^3+

Symbol opnd1 opnd2 value 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

FUIEMS Malik Imran Daud


Evaluate- 623+-382/+*2^3+
Symbol opnd1 opnd2 value opndstk
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

FUIEMS Malik Imran Daud

You might also like