An implementation of the shunting yard that converts infix notation to reversed polish notation.
73 {
74 const unsigned int inputLength = strlen(input);
75 char* operatorStack = (
char*)
malloc(
sizeof(
char) * inputLength);
76
77
78
79 unsigned int stackPointer = 0;
80
81
82
83 char* str =
malloc(
sizeof(
char) * inputLength + 1);
84 strcpy(str,input);
85 char* token = strtok(str," ");
86
87
88
89 output[0] = '\0';
90
91 while (token != NULL) {
92
93 if (isdigit(token[0])) {
94 strcat(output,token);
95 strcat(output," ");
96
97 token = strtok(NULL," ");
98 continue;
99 }
100
101 switch (token[0]) {
102
103 case '(': {
104 operatorStack[stackPointer++] = token[0];
105 break;
106 }
107
108
109 case ')': {
110
111 if(stackPointer < 1) {
112 fprintf(stderr,"Error: Mismatched parentheses\n");
115 return 1;
116 }
117
118 while (operatorStack[stackPointer - 1] != '(') {
119
120 const unsigned int i = (stackPointer--) - 1;
121 strncat(output, &operatorStack[i], 1);
122 strcat(output," ");
123
124
125
126 if(stackPointer == 0) {
127 fprintf(stderr,"Error: Mismatched parentheses\n");
130 return 1;
131 }
132 }
133
134
135
136
137 stackPointer--;
138 break;
139 }
140
141
142 default: {
143
144 if(stackPointer < 1) {
145 operatorStack[stackPointer++] = token[0];
146 break;
147 }
148
149
150 if((stackPointer - 1 > 0) && operatorStack[stackPointer - 1] != '(') {
152 const int precedence2 =
getPrecedence(operatorStack[stackPointer - 1]);
154
155
156 while (
157 ((associativity && precedence1 == precedence2) ||
158
159 precedence2 > precedence1) &&
160
161 ((stackPointer - 1 > 0) && operatorStack[stackPointer - 1] != '(')) {
162
163 strncat(output,&operatorStack[(stackPointer--) - 1],1);
164 strcat(output," ");
165 }
166 }
167
168
169 operatorStack[stackPointer++] = token[0];
170 break;
171 }
172 }
173
174 token = strtok(NULL," ");
175 }
176
178
179
180
181 while (stackPointer > 0) {
182
183
184 if(operatorStack[stackPointer - 1] == '(') {
185 fprintf(stderr,"Error: Mismatched parentheses\n");
187 return 1;
188 }
189
190 const unsigned int i = (stackPointer--) - 1;
191 strncat(output, &operatorStack[i], 1);
192 if (i != 0) {
193 strcat(output," ");
194 }
195 }
196
198 return 0;
199}
#define malloc(bytes)
This macro replace the standard malloc function with malloc_dbg.
Definition malloc_dbg.h:18
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
int getPrecedence(char operator)
for assertion
Definition shunting_yard.c:22
int getAssociativity(char operator)
Helper function that returns each operator's associativity.
Definition shunting_yard.c:48