-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix.c
126 lines (116 loc) · 1.92 KB
/
infix.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct node
{
char data;
struct node *next;
};
struct node* create_a_stack(void);
int isopp(char);
int pre(char,char);
char top(struct node*);
void push(char,struct node*);
int value(char);
void pop(struct node*);
void main()
{
struct node *head;
head = create_a_stack();
char a[10000];
printf("Enter an Expression.\n");
scanf("%s",a);
int n = strlen(a);
int i;
for(i = 0;i < n;i++)
{
if(a[i] == '(')
push(a[i],head);
else if(isalnum(a[i]))
printf("%c ",a[i]);
else if(isopp(a[i]))
{
if(head->next == NULL)
push(a[i],head);
else if(pre(a[i],top(head)) || top(head) == '(')
push(a[i],head);
else
{
while(head->next != NULL && pre(a[i],top(head)) == 0)
{
printf("%c ",top(head));
pop(head);
}
push(a[i],head);
}
}
else if(a[i] == ')')
{
while(top(head) != '(')
{
printf("%c ",top(head));
pop(head);
}
pop(head);
}
}
while(head->next != NULL)
{
if(isopp(((head->next)->data)))
{
printf("%c ",top(head));
pop(head);
}
else if((head->next)->data == '(')
pop(head);
}
}
struct node* create_a_stack()
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = 0;
ptr->next = NULL;
return ptr;
}
int isopp(char c)
{
if(c == '+' ||c == '-' ||c == '/' ||c == '*')
return 1;
else
return 0;
}
char top(struct node *ptr)
{
return ((ptr->next)->data);
}
void push(char c,struct node *ptr)
{
struct node *new_ptr;
new_ptr = (struct node*)malloc(sizeof(struct node));
new_ptr->data = c;
new_ptr->next = ptr->next;
ptr->next = new_ptr;
}
int value(char c)
{
if(c == '*' || c == '/')
return 1;
else if(c == '+' || c == '-')
return 0;
}
int pre(char c,char s)
{
if(value(c) > value(s))
return 1;
else
return 0;
}
void pop(struct node* ptr)
{
struct node *temp;
temp = ptr->next;
ptr->next = temp->next;
free(temp);
}