Repository navigation
Expand file tree
/
Copy path02LinkStackTest2.c
More file actions
133 lines (85 loc) · 1.84 KB
/
Copy path02LinkStackTest2.c
File metadata and controls
133 lines (85 loc) · 1.84 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "LinkStack.h "
/*
模仿编译器完成计算后缀表达式的结果.
算法简单描述:
从左只有扫描表达式字符串,如果是数字则入栈;如果是运算符则依次弹出右操作数\左操作数,计算结果后再入栈;
直到遍历完毕栈中唯一的一个元素即为结果
*/
int isDigit(const char ch){
return (ch >= '0') && (ch <= '9');
}
int isOperate(const char ch){
return (ch == '+') || (ch == '-')||(ch == '*') || (ch == '/');
}
int express(int left, int right, char op){
int ret = 0;
switch (op)
{
case '+':
ret = left + right;
break;
case '-':
ret = left - right ;
break;
case '*':
ret = left * right;
break;
case '/':
ret = left / right;
break;
default:
break;
}
return ret;
}
int value(char ch)
{
return (ch - '0');
}
int computer(const char *exp){
int i = 0,res,num;
LinkStack *stack = LinkStackCreate();
while ( exp[i] != '\0')
{
if (isDigit(exp[i]))
{
//把char转换成int入栈便于计算结果
num = value(exp[i]);
linkStackPush(stack,(void *)num);
if (LinkStackSize(stack) > 0)
{
int temp = (int)LinkStackTop(stack);
}
}
else if (isOperate(exp[i]))
{
int right = (int)LinkStackPop(stack);
int left = (int)LinkStackPop(stack);
res = express(left, right, exp[i]);
linkStackPush(stack, (void *)res);
}
else{
printf("Invalid expression.\n");
break;
}
i++;
}
if (LinkStackSize(stack) != 1 || exp[i] != '\0')
{
printf("Invalid expression.\n");
return -1;
}
res = (int )LinkStackPop(stack);
LinkStackDestroy(stack);
return res;
}
int main(){
int result = computer("831-5*+");
printf("8+(3-1)*5 = %d\n",result);
system("pause");
return EXIT_SUCCESS;
}