You are on page 1of 49

Application of Stacks

Dr. Seema Gupta Bhol


Applications of stacks
• Following are some applications of stacks
– Balance of braces /Parentheses.
– Reversing a Word
– Evaluating postfix expressions

2
Balanced Parentheses
• Each “(”, “{”, or “[” must be paired with a
matching “)”, “}”, or “[”
– correct: ( )(( )){([( )])}
– correct: ((( )(( )){([( )])}
– incorrect: )(( )){([( )])}
– incorrect: ({[ ])}
– incorrect: (

3
Balanced parentheses in an Expression
Algorithm :Balanced Parentheses
• If the element is a starting bracket( ‘{‘, ‘[‘, ‘(‘ ), Push it to the
Stack.
• Similarly for closing bracket( ‘}’, ‘]’, ‘)’ ), pop an element
from he Stack.
• Compare the poped element with the closing bracket. While
the popped element is not the matching starting bracket, we
can conclude that the parentheses are not balanced.
• If the elements are not a starting or closing bracket, we can
assume that they are other characters of the expression. As a
result, we can skip that iteration using the continue statement.
• Finally, if the Stack is empty after the traversal, the
parentheses are said to be balanced else it is not balanced.
Reversing a Word
• We can use a stack to reverse the letters in a
word.
• Read each letter in the word and push it onto
the stack
• When you reach the end of the word, pop the
letters off the stack and print them out.

6
string WELCOME, then on reversing it would be
EMOCLEW.
Notations for Arithmetic Expression
There are three notations to represent an
arithmetic expression:
• Infix Notation
• Prefix Notation
• Postfix Notation
Infix Notation

The infix notation is a convenient way of writing an


expression in which each operator is placed between the
operands.

Infix expressions can be parenthesized or unparenthesized


depending upon the problem requirement.
e.g.
• A+B
• (C - D)
All these expressions are in infix notation because the
operator comes between the operands.
Operator Precedence Rules
In the algebraic expression, the order of the operator
precedence is given in the below table:

Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
Multiplication and *, /
Division
Addition and +,-
Subtraction
Prefix Notation
• The prefix notation places the operator before the
operands.
• This notation was introduced by the Polish mathematician
and hence often referred to as polish notation.

Example:
• +AB
• -CD

All these expressions are in prefix notation because the


operator comes before the operands.
Postfix Notation
• The notation places the operator after the operands.

• This notation is just the reverse of Polish notation and


also known as Reverse Polish notation.
Example:
• AB+
• CD–
All these expressions are in postfix notation because the
operator comes after the operands.

• Expressions are evaluated from left to right.

• Precedence rules and parentheses are never needed!!


Advantages of Postfix Form
• No need to use parentheses for grouping

• No need to use precedence rules


Conversion of Arithmetic Expression into
various Notations

Infix Notation Prefix Notation Postfix Notation


2+5 +25 25+
A*B *AB AB*
(A+B)/C /+ ABC AB+C/
(A*B) + (D-C) +*AB - DC AB*DC-+
Conversion of Arithmetic Expression into
Postfix Notations
1. ((A + B) – C * (D / E)) + F
2. A+B*(C^D-E)^(F+G*H)-I
3. A*(B+C)/D
4. A + B – C
5. A + B * C
6. (A + B) / (C – D)
7. ( ( A + B ) * ( C – D ) + E ) / (F + G)
8. K + L - M*N + (O^P) * W/U/V * T + Q
Solution

1. AB+CDE/*-F+
2. ABCD^E-FGH*+^*+I-
3. ABC+*D/
4. A B + C –
5. A B C * +
6. A B + C D - /
7. A B + C D - * E + F G + /
8. KL+MN∗−OPW∗U/V/T∗+Q+
Evaluation of postfix expressions
Example

*
Computation of Postfix Expressions
WHILE more input items exist
Get an item
IF item is an operand
stack.Push(item)
ELSE
stack.Pop (operand2)
stack.Pop (operand1)
Compute result as(operand1 operator operand2)
stack.Push(result)
stack.Pop(result)
Algorithm for Evaluation of Postfix Expression
1. Add ’)’ to postfix expression.
2. Read postfix expression Left to Right until ) encountered
3. If operand is encountered, push it onto Stack
4. If operator is encountered, Pop two elements
1. A -> Top element
2. B-> Next to Top element
3. Evaluate Result= B operator A
4. Push Result onto Stack
5. Set answer = pop
6. END
expression :
7 8 2 * 4 /+
Expression: 456*+
Postfix expressions: Algorithm using
stacks

*
Evaluation of postfix exprssion: 2 * (4+3) - 5
Infix to postfix conversion
• Use a stack for processing operators (push and pop
operations).
• Scan the sequence of operators and operands from
left to right and perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains
operator of a lower precedence and push the present
operator.

26
Infix to Postfix Conversion
Requires operator precedence information

Operands: Add to postfix expression.

Close parenthesis: Pop stack symbols until an open


parenthesis appears.

Open parenthesis: Push

Operators: Pop all stack symbols until a symbol of lower


precedence appears. Then push the operator.

End of input: Pop all remaining stack symbols and add to


the expression.
27
Converting Infix to Postfix: processing Operator

1. While the stack is not empty & prec(new)  prec(top)

2. pop top off stack and append to postfix

3. push the new operator

28
Consider the infix expression exp = “a+b*c+d”
infix expression exp = “a+b*c+d”
infix expression exp = “a+b*c+d”
infix expression exp = “a+b*c+d”
infix expression exp = “a+b*c+d”
34
35
Expression: A * (B + C * D) + E becomes :A B C D * + * E +

Current Operator Postfix string


symbol Stack
1 A A
2 * * A
3 ( *( A
4 B *( AB
5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
9 ) * ABCD*+
10 + + ABCD *+*
11 E + ABCD*+*E
12 ABCD *+*E+ 36
a –(b + c * d)/e
((A-(B+C))*D)^(E+F)
A^B*C/(D*E-F)
(F-E*D)/C*B^A
Convert infix expression to postfix expression

To convert infix expression to postfix expression,


use the stack .
• Scan the infix expression from left to right.
•Whenever we get an operand, add it to the
postfix expression and
• if we get an operator or parenthesis add it to the
stack by maintaining their precedence.
1. First Start scanning the expression from left to right
2. If the scanned character is an operand, output it, i.e. print it
3. Else
• If the precedence of the scanned operator is higher than the
precedence of the operator in the top of stack or stack is empty or
has opening bracket (, then push operator in the stack
• Else, Pop all the operators, that have greater or equal precedence
than the scanned operator. Once poped ,push this scanned
operator. (If we see a parenthesis while popping then stop and
push scanned operator in the stack)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a
‘(‘ is encountered, and discard both the parenthesis.
6. Now, we should repeat the steps 2 – 6 until the whole infix i.e. whole
characters are scanned.
7. Print output
8. Do the pop and output (print) until stack is not empty
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Function to return precedence of


operators
int prec(char c) {
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
// Function to return associativity of operators
char associativity(char c)
{
if (c == '^')
return 'R';
else
return 'L'; // Default to left-associative
}
// The function to convert infix expression to postfix expression
void infixToPostfix(char s[ ])
{
char result[1000];
int resultIndex = 0;
int len = strlen(s);
char stack[1000];
int stackIndex = -1;
for (int i = 0; i < len; i++)
{
char c = s[i];
// If the scanned character is an operand, add it to the output string.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0'
&& c <= '9'))
{
result[resultIndex++] = c;
}
// If the scanned character is an ‘(‘, push it to the stack.
else if (c == '(')
{
stack[++stackIndex] = c;
}
// If the scanned character is an ‘)’, pop and add to the output string from the
stack until an ‘(‘ is encountered.
else if (c == ')')
{
while (stackIndex >= 0 && stack[stackIndex] != '(')
{
result[resultIndex++] = stack[stackIndex--];
}
stackIndex--; // Pop '('
}
// If an operator is scanned
else {
while (stackIndex >= 0 && (prec(s[i]) <
prec(stack[stackIndex]) || prec(s[i]) = = prec(stack[stackIndex]) &&
associativity(s[i]) == 'L'))
{
result[resultIndex++] = stack[stackIndex--];
}
stack[++stackIndex] = c;
}
}
// Pop all the remaining elements from the stack
while (stackIndex >= 0)
{
result[resultIndex++] = stack[stackIndex--];
}
result[resultIndex] = '\0';
printf("%s\n", result);
}

int main() {
char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
// Function call
infixToPostfix(exp);
return 0;

You might also like