思路:这里实际是把前缀表达式逆序输出转化为类似后序表达式求值:
比如:
输入:+ + 2 * 3 - 7 4 / 8 4 处理成 4 8 / 4 7 - 3 * 2 + + 链表,放到后缀表达式求值程序 postFixEval计算得 | 13.0 |
#include <stdio.h>
#include <stddef.h>#include <string.h>
#include <stdlib.h>
#define MAXSIZE 100
//用链表实现前缀表达式,
typedef struct Node
{
union
{char exp;
int a;
} data;
struct Node *next;
struct Node *prev;
}Node;
int isExpression(int tmpExp){
if(tmpExp=='+'||tmpExp=='-'||tmpExp=='/'||tmpExp=='*'||tmpExp=='('||tmpExp==')')
return 1;
else
return 0;
}
int isSuperior(int tmpExp,int tmpExp2){
if(tmpExp2=='('||(tmpExp=='/'||tmpExp=='*')) //tmpExp2=='('||(tmpExp=='/'||tmpExp=='*')&&(tmpExp2=='+'||tmpExp2=='-')
return 1;
else
return 0;
}
void printNode(Node* node)
{
if(node)
{char tmpExp=node->data.exp;
if(isExpression(tmpExp))
printf("%c",node->data.exp);
else
printf("%d",node->data.a);
if(node)
printNode(node->next);
}
}
typedef struct Stack2
{double arr[MAXSIZE];
int top;
}Stack2;
void push(double num,Stack2 *stack)
{if( stack->top>=MAXSIZE)
return ;
else
{stack->top++;
(stack->arr[stack->top]=num);
}
}
double pop(Stack2 *stack)
{ double ret;
if( stack->top<=-1)
return -1;
else
{ret=stack->arr[stack->top]; stack->top--;}
return ret;
}
// 后缀表达式求值程序
double postFixEval(Node * head)
{ double val=0;
Node * node=head;
Stack2 stack2;
stack2.top=-1;
while(node)
{
if(!isExpression(node->data.exp))
{
push(node->data.a,&stack2);
}
else
{
double op1=pop(&stack2);
double op2=pop(&stack2);
switch (node->data.exp)
{
case '+':
val = op1 + op2;
break;
case '-':
val = op1 - op2; //注意是op1 /op2
break;
case '*':
val = op1 * op2;
break;
case '/':
val = op1 / op2; //注意是op1 /op2
break;
}
push(val,&stack2);
}
node=node->next;
}
return val=pop(&stack2);
}
int main(int argc, char* argv[])
{
Node * head=0;
int i=0,length=0;
char buf[1024];
char* tmpExp,sep[]=" ";
char *p=NULL;
// head=(Node*)malloc(sizeof(Node));
// head->data.exp=' ';
// head->data.a=0;
// head->next=0;
gets(buf);
tmpExp=buf;
Node* tmpExpNode=head;
//输入为前缀表达式
while(p=strtok(tmpExp,sep))
{
Node * node=(Node*)malloc(sizeof(Node));
node->next=0;
// printf("%s",p); p is a point to string (not a point to a char)
if(strcmp(p,"+")==0||strcmp(p,"+")==0||strcmp(p,"-")==0||strcmp(p,"*")==0||strcmp(p,"/")==0||strcmp(p,"(")==0||strcmp(p,")")==0)
sscanf(p,"%c",&node->data.exp);
else
sscanf(p,"%d",&node->data.a);
node->next=tmpExpNode; //逆转输入的前序表达式,即后输入的在前
tmpExpNode=node;
tmpExp=0;
}
printf("%0.1f\n",postFixEval(tmpExpNode)); //0.1f表示一位小数
return 0;
}