-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpression_edit.c
98 lines (93 loc) · 2.61 KB
/
expression_edit.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
#include "stdio.h"
#include "stdlib.h"
// #include "windows.h"
#include "string.h"
typedef struct op
{
char *content;
// double value, grad;//先注释掉
struct op *child[2];
} op;
// void split(char *tmp, char *string, unsigned char start, unsigned char end)
// {
// for (unsigned char i = start; i < end; ++i)
// {
// tmp[i - start] = string[i];
// }
// }
op *new_op(char *string, unsigned char start, unsigned char end)
{
op *tmp_op = (struct op *)malloc(sizeof(struct op));
tmp_op->content = (char *)malloc((end - start + 1) * sizeof(char));
tmp_op->child[0] = NULL;
tmp_op->child[1] = NULL;
memcpy(tmp_op->content, string + start, end - start);
tmp_op->content[end - start] = '\0'; // 手动加上终止符
return tmp_op;
}
op *analyze(char *string, unsigned char start, unsigned char end)
{
// char *tmp_char = (char *)malloc(255 * sizeof(char));//临时缓存区文本
for (unsigned char i = start, tmp = 0; i < end + 1; ++i)
{
if (string[i] == '(') //累加左括号数量
{
tmp++;
}
else if (string[i] == ')') //累减右括号数量
{
tmp--; //积累括号
if (!tmp) //左右括号匹配
{
op *tmp_ch = analyze(string, start + 1, i - 1); //左表达式递归解析
char tmp_symbol = string[i + 1];
op *tmp_op = new_op(string, i + 1, i + 2); //本层级运算符
if (tmp_symbol == 's' || tmp_symbol == 'c' || tmp_symbol == 'g')
{
tmp_op->child[0] = tmp_ch;
}
else
{
tmp_op->child[0] = tmp_ch;
tmp_op->child[1] = analyze(string, i + 3, end - 1); //)+>(<123>)<)
}
return tmp_op;
};
}
}
return new_op(string, start, end + 1); //递归底层返回op //strtod(tmp_char, tmp_char)/* */
}
void op_print(op *unit)
{
printf("\nop:%p content:%s", unit, unit->content);
if (unit->child[0] != NULL)
{
op_print(unit->child[0]);
}
if (unit->child[1] != NULL)
{
op_print(unit->child[1]);
}
}
void op_clean(op *unit)
{
if (unit->child[0] != NULL)
{
op_clean(unit->child[0]);
}
if (unit->child[1] != NULL)
{
op_clean(unit->child[1]);
}
free(unit->content);
free(unit);
}
int main()
{
char tmp[] = "(3.14)+((1.414)*((1.427)+(0.333)))";
op *final = analyze(tmp, 0, strlen(tmp) - 1);
printf("%p", final);
op_print(final);
op_clean(final);
return 0;
}