forked from EDA-UNB-FGA/bibliotecas-EDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculadora_posfixa_inversa.c
executable file
·147 lines (127 loc) · 2.53 KB
/
Calculadora_posfixa_inversa.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node{
char info;
struct Node *prox, *prev;
}node;
node *makeNode(char info){
node *tmp=(node*)malloc(sizeof(node));
tmp->info=info;
tmp->prox=tmp->prev=NULL;
return tmp;
}
node *push(node *topo, node *input){
input->prox=topo;
if(topo!=NULL)input->prox->prev=input;
return input;
}
node *pop(node *topo){
if(topo!=NULL){
node *cpy=topo;
topo=topo->prox;
free(cpy);
return topo;
}else return NULL;
}
void listar(node *topo){
node *cpy=topo;
if(cpy!=NULL)
while(cpy!=NULL){
printf("%c", cpy->info);
cpy=cpy->prox;
}
printf("\n");
}
char *vetorLista(node *list){
node *cpy=list;
int tam=0;
char *name =(char*)malloc(sizeof(char)*400);
while(cpy->prox!=NULL)cpy=cpy->prox;
while(cpy!=NULL){
name[tam++]=cpy->info;
cpy=cpy->prev;
}
name[tam++]='\0';
return name;
}
int processando_string(char * in){
int tam = strlen(in),i,tnum=0;
int numbers[100],a,b;
for(i=0; i<tam; ++i){
switch(in[i]){
case '+':
a=numbers[tnum-1];
b=numbers[tnum-2];
numbers[tnum-2]=(b+a);
--tnum;
break;
case '-':
a=numbers[tnum-1];
b=numbers[tnum-2];
numbers[tnum-2]=b-a;
--tnum;
break;
case '/':
a=numbers[tnum-1];
b=numbers[tnum-2];
numbers[tnum-2]=b/a;
--tnum;
break;
case '*':
a=numbers[tnum-1];
b=numbers[tnum-2];
numbers[tnum-2]=b*a;
--tnum;
break;
default: numbers[tnum++]=(int)(in[i]-'0');
}
}
return numbers[0];
}
int main(){
node *pilha=NULL, *posfixa=NULL;
char string[100], *nomes;
int tam,i;
scanf("%s", string);
tam=strlen(string);
for(i=0; i<tam; i++){
switch(string[i]){
case '(':
pilha=push(pilha,makeNode(string[i]));
break;
case ')':
while(1){
if(pilha->info=='('){
pilha=pop(pilha);
break;
}
posfixa=push(posfixa,makeNode(pilha->info));
pilha=pop(pilha);
}
break;
case '+':
case '-':
while(1){
if(pilha->info=='(')break;
posfixa=push(posfixa,makeNode(pilha->info));
pilha=pop(pilha);
}
pilha=push(pilha,makeNode(string[i]));
break;
case '*':
case '/':
while(1){
if(pilha->info=='(' || pilha->info=='+' || pilha->info=='-')break;
posfixa=push(posfixa,makeNode(pilha->info));
pilha=pop(pilha);
}
pilha=push(pilha,makeNode(string[i]));
break;
default : posfixa=push(posfixa,makeNode(string[i]));
}
}
nomes = vetorLista(posfixa);
printf("%d\n", processando_string(nomes));
return 0;
}