点击查看代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxsize 20
#define true 1
#define false 0
typedef struct st2 {
int top;
char str[maxsize];
}CharStackSize, *CharStack;
//初始化
void init(CharStack cstack)
{
cstack->top = -1;
return;
}
//判空
int CharisEmpty(CharStack cstack)
{
if (cstack->top == -1) {
return true;
}
return false;
}
//判满
int CharisFull(CharStack cstack)
{
if (cstack->top == maxsize - 1) {
return true;
}
return false;
}
//出栈
int CharPop(CharStack cstack, char * ch)
{
if (CharisEmpty(cstack)) {
return false;
}
*ch = cstack->str[cstack->top--];
return true;
}
//进栈
int CharPush(CharStack cstack, char ch)
{
if (CharisFull(cstack)) {
return false;
}
cstack->str[++cstack->top] = ch;
return true;
}
int choose(char ch)
{
if (ch == '+' || ch == '-') {
return 1;
}
else if (ch == '*' || ch == '/') {
return 2;
}
else if(ch == ')'){
return 3;
}
else if (ch == '(') {
return 0;
}
else {
return 0;
}
}
int main(int argc, char *argv[])
{
CharStack cstack = (CharStack)malloc(sizeof(CharStack));
init(cstack);
char biaodashi[50];
scanf("%s",biaodashi);
for (int i = 0; i < strlen(biaodashi); i++) {
if ('0' <= biaodashi[i] && biaodashi[i] <= '9') {
printf("%c", biaodashi[i]);
}
//处理括号
else if(biaodashi[i] == '(' ) {
CharPush(cstack, biaodashi[i]);
}
else if (biaodashi[i] == ')') {
CharPush(cstack, biaodashi[i]);
while (cstack->top != -1) {
char ch;
CharPop(cstack, &ch);
if(ch != '(' && ch != ')')
printf("%c", ch);
if (ch == '(') {
break;
}
}
}
else {
if (choose(biaodashi[i]) <= choose(cstack->str[cstack->top])) {
while (cstack->top != -1) {
char ch;
CharPop(cstack, &ch);
if (ch != '(' && ch != ')')
printf("%c", ch);
if (ch == '(') {
break;
}
//9+(3-1)*3+6/2
}
CharPush(cstack, biaodashi[i]);
//printf("%c", biaodashi[i]);
}
else {
CharPush(cstack, biaodashi[i]);
}
}
}
while (cstack->top != -1) {
char ch;
CharPop(cstack, &ch);
printf("%c", ch);
}
return 0;
}