-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfToRPN.c
More file actions
119 lines (108 loc) · 3.31 KB
/
Copy pathInfToRPN.c
File metadata and controls
119 lines (108 loc) · 3.31 KB
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
// Filename InfToRPN;
// {METATROPO MIAS ENDO8EMATIKHS PARASTASHS SE RPN}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "StChADT.h"
#define MaxExpression 50 //* MEGISTO MEGE8OS ARI8MHTIKHS EKFRASHS *
#define EndMark ';' //* SHMATODOTEI TO TELOS THS ENDO8EMATIKHS EKFRASHS *
#define OperatorSet "+-*/" //* SYNOLO TELESTWN *
int Priority(char Operator);
void ConvertToRPN(char Expression[]);
main()
{
char Expression[MaxExpression]; //* ENDO8EMATIKH EKFRASH *)
int i;
fflush(stdin);
printf("DWSE ENDOTHEMATIKH EKFRASH. DWSE ; GIA TELOS");
i=-1;
do
{
i++;
Expression[i]=getchar();
} while (Expression[i] !=EndMark);
i++;
Expression[i]='\0';
printf("H ENDOTHEMATIKH PARASTASSH SE RPN MORFH:");
ConvertToRPN(Expression);
printf("\n");
system("PAUSE");
}
int Priority(char Operator)
{
switch (Operator)
{
case '(' : return 0;
case '+' : case '-' : return 1;
case '*' : case '/' : return 2;
}
}
void ConvertToRPN(char Expression[])
{
StackType AStack;
int i;
char Token, TopToken;
boolean DonePopping, Wrong;
CreateStack(&AStack);
Wrong=FALSE;
i=0;
Token=Expression[0];
while ((Token!=EndMark) && (!Wrong))
{
while (Expression[i]==' ') //ingnore empty space
i++;
Token=Expression[i];
if (Token=='(') // left parenthesis
Push(&AStack, Token);
else
if (Token==')') // right parenthesis
{
DonePopping=FALSE;
do
{
if (EmptyStack(AStack))
Wrong=TRUE;
else
{
Pop(&AStack, &TopToken);
if (TopToken !='(')
printf("%2c", TopToken);
else
DonePopping= TRUE;
}
} while ((!DonePopping) && (!Wrong));
}
else
if (strchr(OperatorSet, Token) !=NULL) // Operator
{
DonePopping=FALSE;
while ((!EmptyStack(AStack)) && (!DonePopping))
{
Pop(&AStack,&TopToken);
if (Priority(Token)<=Priority(TopToken))
printf("%2c",TopToken);
else
{
Push(&AStack, TopToken);
DonePopping=TRUE;
}
}
Push(&AStack,Token);
}
else
if (Token!=EndMark) //Operator
printf("%2c",Token);
i++;
}// while
//pop stack and print elements of stack
while ((!EmptyStack(AStack)) && (!Wrong))
{
Pop(&AStack,&TopToken);
if (TopToken !='(')
printf("%2c",TopToken);
else Wrong=TRUE;
}
if (Wrong)
printf("Error in infix notation\n");
else printf("\n");
}