7-1 表达式转换 (25 分)
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef struct {
//手写栈,仅符合先进后出原则(水平所限,等我学会写栈,回来再改),用于保存运算符
char *base;
int rear;
int number;
} Stack;
typedef struct{
//顺序队列,用于控制输出顺序
char **base;
int front;
int rear;
} sqQueue;
Stack s1;
sqQueue q1;
char ch[25], chson[25];
int len;
int initStack(Stack& s) //初始化栈
{
s.base = new char[25];
if(!s.base) return false;
s.rear = s.number = 0;
return true;
}
int initsqQueue(sqQueue& s) //初始化队列
{
s.base = new char*[25]; //二维数组初始化,因为数可能是多位数、小数、正负数。
for(int i=0; i<25; i++)
s.base[i] = new char[25];
if(!s.base) return false;
s.front = s.rear = 0;
return true;
}
void Push(Stack& s, char c){
//把运算符压入栈
s.base[s.rear++] = c;
s.number++;
return ;
}
void Push(sqQueue& q, char c[]){
//重载Push()函数,把数压入队列
int len = strlen(c);
for(int i=0