#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
}
#include<stdio.h>#include<iostream>
#include<string>
#include<stack>
using namespace std
int main() {
string str
stack<char>mystack
while (getline(cin, str)) {
printf("\n")
for (int i = 0i <str.size()i++) {
if (str[i] == 'a' or str[i]==',') {
cout <<str[i]
}
else if (str[i] == '+' or str[i] == '-' or str[i] == '*' or str[i] == '/' ) {
mystack.push(str[i])
}
else if (str[i] == '(') {
cout <<str[i]
}
else if (str[i] == ')') {
cout <<str[i] <<mystack.top()
mystack.pop()
}
}
}
}
是给你一个中缀或者后缀表达式
让你求
前缀表达式
么?用数据结构里树的遍历来实现。前缀表达式就是先根序遍历,中缀表达式就是
中序遍历
,后缀表达式就是
后序遍历
。用一个栈来实现就行