0% found this document useful (0 votes)
12 views13 pages

Stack Apllication in DS

The document outlines various applications of the Stack data structure, including expression evaluation, parenthesis matching, and expression conversion. It provides detailed explanations and examples for converting infix expressions to both prefix and postfix notations using stacks. Additionally, it includes C code implementations for these conversions, demonstrating the practical use of stacks in handling arithmetic expressions.

Uploaded by

Soumya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views13 pages

Stack Apllication in DS

The document outlines various applications of the Stack data structure, including expression evaluation, parenthesis matching, and expression conversion. It provides detailed explanations and examples for converting infix expressions to both prefix and postfix notations using stacks. Additionally, it includes C code implementations for these conversions, demonstrating the practical use of stacks in handling arithmetic expressions.

Uploaded by

Soumya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Stack applications in data structure

Following are some of the important applications of a Stack data structure:

1. Stacks can be used for expression evaluation.


2. Stacks can be used to check parenthesis matching in an expression.
3. Stacks can be used for Conversion from one form of expression to another.
4. Stacks can be used for Memory Management.
5. Stack data structures are used in backtracking problems.

Expression Evaluation

Stack data structure is used for evaluating the given expression. For example, consider the
following expression
5 * ( 6 + 2 ) - 12 / 4
Since parenthesis has the highest precedence among the arithmetic operators, ( 6 +2 ) = 8 will
be evaluated first. Now, the expression becomes
5 * 8 - 12 / 4
* and / have equal precedence and their associativity is from left-to-right. So, start evaluating
the expression from left-to-right.
5 * 8 = 40 and 12 / 4 = 3
Now, the expression becomes
40 - 3
And the value returned after the subtraction operation is 37.
Parenthesis Matching
Given an expression, you have to find if the parenthesis is either correctly matched or not.
For example, consider the expression ( a + b ) * ( c + d ).
In the above expression, the opening and closing of the parenthesis are given properly and
hence it is said to be a correctly matched parenthesis expression. Whereas, the expression, (a
+ b * [c + d ) is not a valid expression as the parenthesis are incorrectly given.
Expression Conversion

Converting one form of expressions to another is one of the important applications of


stacks.

 Infix to prefix
 Infix to postfix
 Prefix to Infix
 Prefix to Postfix
 Postfix to Infix
 Postfix to Infix

Infix to Prefix conversion using stack


Now, let us see how to convert an expression from infix to prefix.

 Infix notation ( a operator b ): For example, a + b is an infix notation.


 Prefix notation ( operator a b ): + a b is the equivalent prefix
notation of a + b.

The compiler scans the given expression either from left to right or from right to left.

Consider the below expression: a + b / c - d

 At first, compiler scans the expression to evaluate the expression b /


c, then scans the expression again to add a to it. The result is
then subtracted with d after another scan.
 This repeated scanning makes the process very inefficient and time
consuming. It will be much easier if the expression is converted
to prefix (or postfix) before evaluation.
 The corresponding expression in prefix form is: -+a/bcd. The prefix
expressions can be easily evaluated using a stack.

Steps to convert infix expression to prefix

1. First, reverse the given infix expression.


2. Scan the characters one by one.
3. If the character is an operand, copy it to the prefix notation output.
4. If the character is a closing parenthesis, then push it to the stack.
5. If the character is an opening parenthesis, pop the elements in the
stack until we find the corresponding closing parenthesis.
6. If the character scanned is an operator

 If the operator has precedence greater than or equal to the top of the
stack, push the operator to the stack.
 If the operator has precedence lesser than the top of the stack, pop
the operator and output it to the prefix notation output and then check
the above condition again with the new top of the stack.

7. After all the characters are scanned, reverse the prefix notation output.

For example, consider the infix expression a/b-(c+d)-e.

After reversing, the notation becomes, e-(d+c)-b/a. While reversing, change open
parenthesis to closed parenthesis and vice versa.

Now, reverse the PREFIX NOTATION from the table,


The prefix notation of the infix expression a/b-(c+d)-e is --/ab+cde.
Now, let us see a C program to convert an infix expression to prefix expression
#include<stdio.h>
#include<math.h>
#include<string.h>
#include <stdlib.h>
#define MAX 20
void push(int);
char pop();
void infix_to_prefix();
int precedence (char);
char stack[20],infix[20],prefix[20];
int top = -1;

int main()
{
printf("\nINPUT THE INFIX EXPRESSION : ");
scanf("%s",infix);
infix_to_prefix();
return 0;
}
// method that pushes the elements onto the character stack
void push(int pos)
{
if(top == MAX-1)
{
printf("\nSTACK OVERFLOW\n");
}
else {
top++;
stack[top] = infix[pos];
}}
// method that removes character from stack and returns them
char pop()
{
char ch;
if(top < 0)

{
printf("\nSTACK UNDERFLOW\n");
exit(0);
}
else
{
ch = stack[top];
stack[top] = '\0';
top--;
return(ch);
}
return 0;
}
// method that converts String from infix to prefix
// all the strings are assumed to be valid expressions
void infix_to_prefix()
{
int i = 0,j = 0;
strrev(infix); // Reverse the infix expression
while(infix[i] != '\0')

// if an alphabet is found then copy it to the output string

if(infix[i] >= 'a' && infix[i] <= 'z')


{
prefix[j] = infix[i];
j++;
i++;
}
// In the reversed string, closing bracket will be found first so put it in the stack
else if(infix[i] == ')' || infix[i] == '}' || infix[i] == ']')
{
push(i);
i++;

}
// if an opening bracket is found, then
else if(infix[i] == '(' || infix[i] == '{' || infix[i] == '[') /* when closing bracket is found */
{
if(infix[i] == '(')
{
while(stack[top] != ')') /* pop till opening bracket is found */
{
prefix[j] = pop();
j++;
}
pop();
i++;
}
else if(infix[i] == '[')
{
while(stack[top] != ']') /* pop till corresponding opening bracket is found */
{
prefix[j] = pop();
j++;
}
pop();
i++;

}
else if(infix[i] == '{')
{
while(stack[top] != '}') /*pop till corresponding opening bracket is found*/
{
prefix[j] = pop();
j++;
}
pop();
i++;
}}
else
{
// if the stack if empty, then we simply put the operator in stack
if(top == -1)
{
push(i);
i++;
}
// if the precedence of operator is less than the stack top then
else if( precedence(infix[i]) < precedence(stack[top]))
{
prefix[j] = pop(); // pop the stack top and add it to the prefix string
j++;
// if you have an operator that has precedence greater than operator
while(precedence(stack[top]) > precedence(infix[i])){
prefix[j] = pop(); // Pop the operator
j++;
if(top < 0) {
break;
}}
push(i);
i++;
}
// if the precedence of operator is greater than or equal to the stack top
else if(precedence(infix[i]) >= precedence(stack[top]))
{
push(i); // Push it onto the stack
i++;
}}}
// At the end remove all the operators from the stack
while(top != -1)
{
prefix[j] = pop();
j++;
}
// Reverse the final string before output
strrev(prefix);
prefix[j] = '\0';
printf("EQUIVALENT PREFIX NOTATION : %s ",prefix);
}

/* Function to return precedence of operators */


int precedence(char alpha)
{
if(alpha == '+' || alpha =='-')
{
return(1);
}
if(alpha == '*' || alpha =='/')
{
return(2);
}
return 0;
}

Infix to Postfix conversion using stack


Expression conversion is the most important application of stacks. Given an infix
expression, it can be converted to both postfix and prefix notations. Now, let us see
how to convert an infix expression to postfix.

 Infix notation ( a operator b ): For example, a + b is an infix notation.


 Postfix notation ( a b operator ): a b + is the equivalent postfix
notation of a + b.

The compiler scans the given expression either from left to right or from right to left.

Consider the below expression: a + b / c - d

 At first, compiler scans the expression to evaluate the expression b /


c, then scans the expression again to add a to it. The result is
then subtracted with d after another scan.
 This repeated scanning makes the process very inefficient and time
consuming. It will be much easier if the expression is converted to
postfix (or prefix) before evaluation.
 The corresponding expression in postfix form is: abc/+d-. The postfix
expressions can be easily evaluated using a stack.
Steps to convert infix expression to postfix

1. Scan the given infix expression from left to right.


2. If the scanned character is an operand, then output it.
3. Else,

 If the precedence of the scanned operator is greater than the


precedence of the operator in the top of the stack(or the stack is
empty or if the stack contains a ‘(‘ ), push it.
 Else, Pop all operators from the stack whose precedence is greater
than or equal to that of the scanned operator. Then, push the
scanned operator to the top of the stack. (If you encounter
parenthesis while popping then stop there and push the scanned
operator in the stack.)

4. If the scanned character is ‘(‘, push it to the stack.


5. If the scanned character is ‘)’, pop the stack and and output characters until ‘(‘ is
encountered, and discard both the parenthesis.
6. Repeat steps 2-5 until infix expression is scanned completely.
7. Print the output.
8. Pop and output from the stack.

Example:

Convert A * (B + C) * D to postfix notation.

Move Curren Ttoken Stack Output


1 A empty A
2 * * A
3 ( (* A
4 B (* AB
5 + +(* AB
6 C +(* ABC
7 ) * ABC+
8 * * ABC+*
9 D * ABC+*D
10 empty
Notes:
In this table, the stack grows toward the left. Thus, the top of the stack is the leftmost
symbol.
In move 3, the left paren was pushed without popping the * because * had a lower
priority then "(".
In move 5, "+" was pushed without popping "(" because you never pop a left
parenthesis until you get an incoming right parenthesis. In other words, there is a
distinction between incoming priority, which is very high for a "(", and instack priority,
which is lower than any operator.
In move 7, the incoming right parenthesis caused the "+" and "(" to be popped but
only the "+" as written out.
In move 8, the current "*" had equal priority to the "*" on the stack. So the "*" on the
stack was popped, and the incoming "*" was pushed onto the stack.

Example:

Evaluate the expression 2 3 4 + * 5 * which was created by the previous algorithm for infix to postfix.

Move Current Token Stack (grows toward left)


1 2 2
2 3 32
3 4 432
4 + 72
5 * 14
6 5 5 14
7 * 70
Notes:
Move 4: an operator is encountered, so 4 and 3 are popped,
summed, then pushed back onto stack.
Move 5: operator * is current token, so 7 and 2 are popped,
multiplied, pushed back onto stack.
Move 7: stack top holds correct value.
Notice that the postfix notation has been created to properly reflect
operator precedence. Thus, postfix expressions never need
parentheses.
For example, consider the infix expression a/b-(c+d)-e.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <string.h>

/* Variable declarations */
char infix_string[20], postfix_string[20];
int top;
int stack[20];

int pop();
int precedence(char symbol);
int isEmpty();
void infix_to_postfix();
int check_space(char symbol);
void push(long int symbol);

int main()
{
int count, length;
char temp;
top = -1;
printf("\nINPUT THE INFIX EXPRESSION : ");
scanf("%s", infix_string);
infix_to_postfix();
printf("\nEQUIVALENT POSTFIX EXPRESSION : %s\n", postfix_string);
return 0;
}

/* Function to convert from infix to postfix */


void infix_to_postfix()
{
unsigned int count, temp = 0;
char next;
char symbol;
for(count = 0; count < strlen(infix_string); count++)
{
symbol = infix_string[count]; // Scanning the input expression
if(!check_space(symbol))
{
switch(symbol)
{
case '(': push(symbol);
break;
case ')':
while((next = pop()) != '(') // pop until '(' is encountered
{
postfix_string[temp++] = next;
}
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while(!isEmpty() && precedence(stack[top]) >= precedence(symbol)) // Check precedence and push
the higher one
postfix_string[temp++] = pop();
push(symbol);
break;
default:
postfix_string[temp++] = symbol;
}
}
}
while(!isEmpty())
{
postfix_string[temp++] = pop();
}
postfix_string[temp] = '\0';
}

/* Function to check precedence of operators */


int precedence(char symbol)
{
switch(symbol)
{
case '(': return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return 0;
}
}

int check_space(char symbol)


{
if(symbol == '\t' || symbol == ' ' )
{
return 1;
}
else
{
return 0;
}
}

void push(long int symbol)


{
if(top > 20)
{
printf("Stack Overflow\n");
exit(1);
}
top = top + 1;
stack[top] = symbol; // Push the symbol and make it as TOP
}

int isEmpty()
{
if(top == -1)
{
return 1;
}
else
{
return 0;
}
}

int pop()
{
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return(stack[top--]); // Pop the symbol and decrement TOP
}

You might also like