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 MAX 5
typedef struct stack
{
char data[MAX];
int top;
}st;
void createStack(st *s)
{
s->top=-1;
}
void push(st *s,char ele)
{
s->top++;
s->data[s->top]=ele;
}
char pop(st *s)
{
return(s->data[s->top--]);
}
int priority(char symbol)
{
switch(symbol)
{
case '+':
case '-':return(2);
case '*':
case '/':return(4);
case '^':return(5);
case '(':
case ')':
case '#':return(1);
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '^':return(1);
default:return(0);
}
}
void convert(char *infix,st *s)
{
char *prefix,symbol;
int i=0,j=0;
prefix=(char *)malloc(sizeof(char)*50);
infix=strrev(infix);/*reverse the infix expression*/
s->data[++(s->top)]='#';/*'#' delimeter is used for end of expression*/
while(infix[i]!='\0')
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
/*if symbol is operand then add it to prefix expression*/
prefix[j]=symbol;
j++;
}
else if(symbol==')')
{
/*if it is closing parentheses then push it to stack*/
push(s,symbol);
}
else if(symbol=='(')
{
/*if it is opening parentheses then pop operators from stack until corresponding parentheses is encountered*/
while(s->data[s->top]!=')')
{
prefix[j]=pop(s);
j++;
}
pop(s);/*pop and discard the closing parentheses*/
}
else
{
/*if the incoming priority of operator is greater or equal to stack top operator then push it into stack*/
if(priority(symbol)>=priority(s->data[s->top]))
{
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.