-
Notifications
You must be signed in to change notification settings - Fork 0
/
unt.c
executable file
·112 lines (101 loc) · 2.07 KB
/
unt.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<stdio.h>
#include<ctype.h>
typedef struct stack
{
int data[50]; //stack array
int top; //pointer to top
}stack;
int precedence(char);
void init(stack *);
int empty(stack *);
int top(stack *p);
int full(stack *s);
void push(stack *s, int x);
int pop(stack *s);
void convert(char infix[],char postfix[])
void main()
{
char infix[50],postfix[50];
printf("Enter an infix expression: ");
gets(infix);
convert(infix,postfix); //function call to convert
printf("\n PF is %s \n",postfix);
}
void convert(char infix[],char postfix[])
{
stack s;
char x,token; //token is the current scanned element
int i,j;
init(&s); //initialising the structure
j=0;
for(i=0; infix[i]!='\0'; i++)
{
token=infix[i];
if(isalnum(token))
postfix[j++]=token; //adding token into postfix array
else
if(token=='(')
push(&s,'(');
else
if(token==')')
while((x=pop(&s))!='(')
postfix[j++]=x;
else
{
while(precedence(token)<=precedence(top(&s))&&!empty(&s))
{
x=pop(&s);
postfix[j++]=x;
}
push(&s,token);
}
}
while(!empty(&s))
{
x=pop(&s);
postfix[j++]=x;
}
postfix[j]='\0';
}
int precedence(char x)
{
if(x=='(')
return (0);
if(x=='+'||x=='-')
return (1);
if(x=='*'||x=='/')
return (2);
return (3);
}
void init(stack *s)
{
s->top = -1; //actually, new function is not required, could've been done into main()???
}
int empty(stack *s)
{
if(s->top==-1)
return (1);
return (0);
}
int full(stack *s)
{
if (s->top=49)
return (1);
return (0);
}
void push(stack *s, int x)
{
s->top=s->top+1;
s->data[s->top]=x;
}
int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return (x);
}
int top(stack *p)
{
return(p->data[p->top]);
}