思路:采用栈存储运算符,(运算符之间优先级为 ‘(’ ‘)’ <’+’ ‘-’<’*’ ‘/’)
当输入字符为a——z时直接输出;
当输入字符为‘(’或栈为空时,直接入栈
当输入字符为‘)’时,出栈直到对应的 ‘(’
当输入字符为其他时,如果栈顶元素的优先级小于输入字符的优先级,直接将输入字符入栈;如果栈顶元素优先级大于等于输入字符优先级,则将栈顶元素出栈并输出,然后将输入字符入栈。
//逆波兰式 (根据优先级)
#include "stdio.h"
#include "stdlib.h"
typedef struct StackNode{
char elem;
struct StackNode *next;
} StackNode,*StackNodePtr;
typedef struct Stack{
StackNodePtr top;
}Stack,*StackPtr;
void Push(char c,StackPtr S)
{
StackNodePtr P;
P = (StackNodePtr)malloc(sizeof(StackNode));
P->elem = c;
P->next = S->top;
S->top = P;
}
char Pop(StackPtr S){
char s;
if(S->top == NULL)
printf("Error");
else
{
StackNodePtr P;
P = S->top;
s = P->elem;
S->top = P->next;
free(P);
return s;
}
}
void InfixToPostfix(StackPtr F){
char c = getchar();
while(c != '\n')
{
if(c <= 'z' && c >= 'a')
printf("%c",c);
else
{
if(F->top == NULL)
{
Push(c,F);
}
else
{
if(c == '(')
{
Push(c,F);
}
else if(c == ')')
{
while(F->top->elem != '(')
{
char s = Pop(F);
printf("%c",s);
}
Pop(F);//把'('出栈
}
else if(c == '+' || c == '-')
{
//如果小于等于栈顶优先级,就把栈顶输出,然后入栈,否则直接入栈
if(F->top->elem == '(')
{
Push(c,F);
}
else
{
char s = Pop(F);
printf("%c",s);
Push(c,F);
}
}
else if(c == '*' || c == '/')
{
Push(c,F);
}
}
}
c = getchar();
}
while(F->top != NULL)
{
char s = Pop(F);
printf("%c",s);
}
}
int main(){
StackPtr F; //F 运算符和括号 N 字母
F = (StackPtr)malloc(sizeof(Stack));F->top = NULL;
InfixToPostfix(F);
return 0;
}
第二版:
#include <stdlib.h>
#include <stdio.h>
//利用优先级;栈存储符号,字符直接输出;
//( < );
typedef struct Node{
char data;
struct Node *next;
}Node,*PNode;
typedef struct Stack{
PNode top;
}Stack,*PStack;
void Push(PStack S,char c){
PNode p;
p = (PNode)malloc(sizeof(Node));
p->data = c;
p->next = S->top;
S->top = p;
}
char Pop(PStack S){
char c = '0';
PNode p;
if(S->top == NULL)
{
printf("kong");
}
else
{
p = S->top;
c = p->data;
S->top = p->next;
free(p);
}
return c;
}
void InfixToPostfix(){
PStack s;
s = (PStack)malloc(sizeof(Stack));
s->top = NULL;
char out;
while(1){
char c = getchar();
if(c == '\n') break;
if(c <= 'z' && c >= 'a')
printf("%c",c);
else
{
if(s->top == NULL)
Push(s,c);
else
{
switch(c){
case('('):Push(s,c);
break;
case(')'):{//弹出到‘(’
while(s->top->data != '(')
{
out = Pop(s);
printf("%c",out);
}
out = Pop(s);
}
break;
case('+'):
case('-'):{
if(s->top->data == '(')
{
Push(s,c);
}
else //if(s->top == '*' || s->top == '/'||)
{
out = Pop(s);
printf("%c",out);
Push(s,c);
}
}
break;
case('*'):
case('/'):{
if(s->top->data == '*' || s->top->data == '/')
{
out = Pop(s);
printf("%c",out);
Push(s,c);
}
else
{
Push(s,c);
}
}
break;
}
}
}
}
while(s->top != NULL)
{
char out = Pop(s);
printf("%c",out);
}
}
int main(){
InfixToPostfix();
return 0;
}