2 1.000+2/4= ((1+2)*5+1)/4=
1.000 2 4 / + = 1 2 + 5 * 1 + 4 / =
解题思路:逆波兰式算法的实现:
代码如下:# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define False 0
# define True 1
typedef struct node
{
char data;
struct node *next;
}LinkStackNode, *LinkStack;
int InitStack(LinkStack *S) //初始化栈
{
(*S) = (LinkStack)malloc(sizeof(LinkStackNode));
(*S)->next = NULL;
if ((*S) != NULL)
return True;
else
return False;
}
int Push(LinkStack S, char x) //进栈
{
LinkStack temp;
temp = (LinkStack)malloc(sizeof(LinkStackNode));
if (temp == NULL)
return False;
temp->data = x;
temp->next = S->next;
S->next = temp;
return True;
}
int Pop(LinkStack S) //出栈
{
LinkStack temp;
temp = S->next;
if (temp == NULL)
return False;
S->next = temp->next;
free(temp);
return True;
}
int top(LinkStack S)
{
char e;
e = S->next->data;
return e;
}
//*************************************************************************
int cmp(char ch)
{
switch(ch)
{
case‘+‘:
case‘-‘:return 1;
case‘*‘:
case‘/‘:return 2;
default:return 0;
}
}
void fun(char *a, char *b,LinkStack s)
{
Push(s,‘#‘);
int i = 0,j = 0;
while (i < strlen(a) - 1)
{
if (a[i] == ‘(‘)
{
Push(s,a[i]);
i++;
}
else if (a[i] == ‘)‘)
{
while (top(s) != ‘(‘)
{
b[j] = top(s);
b[j+1] = ‘ ‘;
j+=2;
Pop(s);
}
Pop(s);
i++;
}
else if (a[i] == ‘+‘ || a[i] == ‘-‘ || a[i] == ‘*‘ || a[i] == ‘/‘)
{
while (cmp(top(s)) >= cmp(a[i]))
{
b[j] = top(s);
b[j+1] = ‘ ‘;
j+= 2;
Pop(s);
}
Push(s,a[i]);
i++;
}
else
{
while (‘0‘ <= a[i] &&a[i] <= ‘9‘ ||a[i] == ‘.‘)
{
b[j] = a[i];
i++;j++;
}
b[j] = ‘ ‘;
j++;
}
}
while (top(s) != ‘#‘)
{
b[j] = top(s);
b[j+1] = ‘ ‘;
j += 2;
Pop(s);
}
b[j] = ‘=‘;
}
int main(void)
{
int n,i;
char a[1001],b[2002];
LinkStack S;
scanf("%d", &n);
while (n--)
{
InitStack(&S);
scanf("%s", a);
fun(a,b,S);
i = 0;
while (b[i] != ‘=‘)
{
printf("%c",b[i]);
i++;
}
printf("=\n");
}
return 0;
}
原文地址:http://blog.csdn.net/java_oracle_c/article/details/41986941