This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
STACK2.c
105 lines (97 loc) · 2.42 KB
/
STACK2.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
#include <stdio.h>
int top=-1, n, i, TOP=-1;
char input[100], stack[100], ans[100];
int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
int checkoprand(char ch){
if(ch>='a' && ch<='z'){
return 1;
}
if(ch>='A' && ch<='Z'){
return 1;
}
else{
return 0;
}
}
int main() {
gets(input);
while(input[n]!=0){
n++;
}
for(int i =0; i<n; i++){
if(checkoprand(input[i])==1){
top++;
ans[top] = input[i];
}
else{
if(TOP==-1 || input[i]=='('){
TOP++;
stack[TOP]=input[i];
}
else if(Prec(input[i])==Prec(stack[TOP])){
if(Prec(input[i]) == 3 && Prec(stack[TOP]) == 3){
TOP++;
stack[TOP] = input[i];
}
else{
top++;
ans[top] = stack[TOP];
stack[TOP] = input[i];
}
}
else if(input[i]==')' || Prec(input[i])<Prec(stack[TOP])){
while(TOP!=-1 || stack[TOP]=='('){
if(stack[TOP]!='('){
top++;
ans[top] = stack[TOP];
stack[TOP] = '\0';
TOP--;
}
else{
break;
}
}
if(input[i]!='(' && input[i]!=')')
{
TOP++;
stack[TOP] = input[i];
}
}
else if(Prec(input[i])>Prec(stack[TOP])){
TOP++;
stack[TOP]=input[i];
}
}
if(i==n-1){
if(TOP!= -1){
while(TOP!=-1){
if(stack[TOP]!='(' && stack[TOP]!=')'){
top++;
ans[top] = stack[TOP];
stack[TOP] = '\0';
TOP--;
}
else{
stack[TOP] = '\0';
TOP--;
}
}
}
}
}
printf("%s", ans);
}