1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 50
int top=-1;
push(char *stack,char elem)
{
stack[++top]=elem;
}
char pop(char *stack)
{
return(stack[top--]);
}
int priority(char ch) //priority for different operators
{
if(ch=='^')
{
return(5);
}
else if(ch=='*' || ch=='/')
{
return(4);
}
else if(ch=='+' || ch=='-')
{
return(3);
}
else
{
return(2);
}
}
void infix_pofix(char *infix)
{
int length;
char *stack;
static int index=0,pos=0;
char symbol,temp;
char *postfix;
//dynamic array allocation for stack and postfix expression
stack=(char *)malloc(sizeof(char)*SIZE);
postfix=(char *)malloc(sizeof(char)*100);
length=strlen(infix);
while(index<length)
{
//take one by one symbol from infix expression
symbol=infix[index];
//cases for different operators
switch(symbol)
{
case '(': push(stack,symbol);
break;
case ')': temp=pop(stack);
while(temp!='(')
{
/*if the symbol is closing parentheses then repeatedly pop from the stack until correspondin opening parentheses
is encountered*/
postfix[pos]=temp;
pos++;
temp=pop(stack);
}
break;
case '^':
case '+':
case '-':
case '*':
case '/':while(priority(stack[top])>=priority(symbol))
{
/*if the precedence of the stack operator is greater or equal to precedence of incoming operator then pop and add to
postfix expression, otherwise push the operator into stack*/
temp=pop(stack);
postfix[pos]=temp;
pos++;
}
push(stack,symbol);
break;
default:postfix[pos++]=symbol;
break;
}
index++;
}
while(top>=0)
{
/*pop one by one symbol from the stack*/
temp=pop(stack);
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.