-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInfix to postfix conversion
113 lines (96 loc) · 2.08 KB
/
Infix to postfix conversion
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
113
/*logic is (AT GFG) that in the stack lower priority operator cannot be put above higher priority operator and Ravi sir's algo is different
in that when + is compared with ( ,+ will have lower priortiy and when ( is compared with + then ( will have lower priority */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
struct node{
int data;
struct node *link;
};
struct node *head=NULL;
void push(char x)
{
struct node* p=(struct node*) malloc (sizeof(struct node));
if(p==NULL)
{
printf("overflow");
return;
}
p->data=x;
// p->link=NULL;
p->link=head;
head=p; //here head acts like top
}
char pop()
{
char item;
struct node *p;
if(head==NULL){
//printf("underflow");
return -1;
}
item=head->data;
p=head;
head=head->link;
free(p);
return item;
}
int match(char x)
{
switch (x)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
void check()
{
char value,arr[10000];
scanf("%s",arr);
int i=0;
while(arr[i])
{
value=arr[i];
if((value>='a'&&value<='z')||(value>='A'&&value<='Z'))
printf("%c",value);
else if(value=='(')
push(value);
else if(value==')'){
//printf("P%c \n",value);
while(head!=NULL&&head->data!='(')
printf("%c",pop());
if (head!=NULL&&head->data!='(')
printf("invalid"); // invalid expression
else
pop();
}
else
{
while(head!=NULL&&(match(head->data)>=match(value)))
printf("%c",pop());
push(value);
}
i++;
}
while(head!=NULL)
printf("%c",pop());
}
int main()
{
int x,T,t=0,n,i;
scanf("%d",&n);
while(n--){
(check());
printf("\n");
}
return 0;
}