-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.c
107 lines (100 loc) · 3.22 KB
/
convert.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "node.h"
#include "value.h"
#include "stack.h"
#include "queue.h"
#include "convert.h"
/*
* convert.c - A conversion class for converted a queued expression into postfix. Also contains a helper function for this
* - Returns another queue with the postfix saved into this queue
* - written by Kurt Anderson
* - Last Updated 9/8/2016
*/
int priority(char *x);
struct queue *convertPost(queue *pQueue) { //Converts a Given Queue into a Postfix Queue
struct value *evalVal;
struct node *evalNode;
char *evalString;
int x = 0;
int length = pQueue->length;
struct stack *postEvaluator = newStack();
struct queue *postQueue = newQueue();
while (x < length){
struct value *tempValue = dequeue(pQueue);
struct node * tempNode;
if (tempValue->type == 0){
tempNode = newNode(tempValue);
enqueue(postQueue,tempNode);
}
else if (tempValue->type == 1){
tempNode = newNode(tempValue);
enqueue(postQueue,tempNode);
}
else if (tempValue->type == 2){
tempNode = newNode(tempValue);
if (strcmp(tempValue->sVal,"(") == 0) {//Checks and Maintain Parenthesis
push(postEvaluator,tempNode);
}
else {
if (strcmp(tempValue->sVal, ")") == 0){
evalVal = pop(postEvaluator);
evalString = evalVal->sVal;
while(strcmp(evalString,"(") != 0){
evalNode = newNode(evalVal);
enqueue(postQueue, evalNode);
evalVal = pop(postEvaluator);
evalString = evalVal->sVal;
}
}
else {
if(postEvaluator->size > 0){
while(priority(tempValue->sVal) <= priority(peekStack(postEvaluator)->sVal)){ //Checks priority of opers
evalVal = pop(postEvaluator);
evalNode = newNode(evalVal);
enqueue(postQueue, evalNode);
if (postEvaluator->size == 0){
break;
}
}
}
push(postEvaluator, tempNode);
}
}
}
x++;
}
while(postEvaluator->size > 0){
evalVal = pop(postEvaluator);
evalNode = newNode(evalVal);
enqueue(postQueue,evalNode);
}
return postQueue;
}
//Calculates the priority of an Operand using the PEMDAS rules. Returns an int value, with higher priority being lower numbers
int priority(char *x){ //Chooses process
if (strcmp(x,"(")== 0){
return(0);
}
if (strcmp(x,"+") == 0){
return(1);
}
if (strcmp(x,"-") == 0){
return(1);
}
if (strcmp(x,"*") == 0){
return(2);
}
if (strcmp(x,"/") == 0){
return(2);
}
if (strcmp(x, "%") == 0){
return(3);
}
if (strcmp(x, "^") == 0){
return(4);
}
return(10);
}