void inTopast(char* str) //中缀到后缀 { int slen = strlen(str); //字符长度 int top = -1; //栈顶 top++; for(int i = 0; i < slen; i++) //正序 { char c = str[i]; //提取一字符 switch(c) //比较 { //'(','+','-','*','/'入栈 //')'输出栈中到'('的元素 //其他字符直接输出 case '(' : stacks[top++].s = c; break; case ')' : while(stacks[--top].s != '(') cout << stacks[top].s; break; case '+' : stacks[top++].s = c; break; case '-' : stacks[top++].s = c; break; case '*' : stacks[top++].s = c; break; case '/' : stacks[top++].s = c; break; default : cout << c; } } cout << endl; }
void inToprev(char* str) //中缀到前缀 { int slen = strlen(str); //字符长度 int top = -1; //栈顶 top++; char res[MAX_LENGTH]; int num = 0; for(int i = slen -1; i >= 0; i--) //逆序 { char c = str[i]; //提取一字符 switch(c) //比较 { //')','+','-','*','/'入栈 //'('保存栈中到')'的元素 //其他字符直接保存 case ')' : stacks[top++].s = c; break; case '(' : while(stacks[--top].s != ')') res[num++] = stacks[top].s; break; case '+' : stacks[top++].s = c; break; case '-' : stacks[top++].s = c; break; case '*' : stacks[top++].s = c; break; case '/' : stacks[top++].s = c; break; default : res[num++] = c; } } //将保存的字符串逆序输出就是前缀表达式 for(int i = num - 1; i >= 0; i--) cout << res[i]; cout << endl; }
#include <iostream> #include <cstring> using namespace std; int const MAX_LENGTH = 100; typedef struct { char s; }Stacks; //栈结构定义 Stacks stacks[MAX_LENGTH]; //栈 void inTopast(char* str) //中缀到后缀 { int slen = strlen(str); //字符长度 int top = -1; //栈顶 top++; for(int i = 0; i < slen; i++) //正序 { char c = str[i]; //提取一字符 switch(c) //比较 { //'(','+','-','*','/'入栈 //')'输出栈中到'('的元素 //其他字符直接输出 case '(' : stacks[top++].s = c; break; case ')' : while(stacks[--top].s != '(') cout << stacks[top].s; break; case '+' : stacks[top++].s = c; break; case '-' : stacks[top++].s = c; break; case '*' : stacks[top++].s = c; break; case '/' : stacks[top++].s = c; break; default : cout << c; } } cout << endl; } void inToprev(char* str) //中缀到前缀 { int slen = strlen(str); //字符长度 int top = -1; //栈顶 top++; char res[MAX_LENGTH]; int num = 0; for(int i = slen -1; i >= 0; i--) //逆序 { char c = str[i]; //提取一字符 switch(c) //比较 { //')','+','-','*','/'入栈 //'('保存栈中到')'的元素 //其他字符直接保存 case ')' : stacks[top++].s = c; break; case '(' : while(stacks[--top].s != ')') res[num++] = stacks[top].s; break; case '+' : stacks[top++].s = c; break; case '-' : stacks[top++].s = c; break; case '*' : stacks[top++].s = c; break; case '/' : stacks[top++].s = c; break; default : res[num++] = c; } } //将保存的字符串逆序输出就是前缀表达式 for(int i = num - 1; i >= 0; i--) cout << res[i]; cout << endl; } int main() { //测试数据 char str1[] = "((a+b)*c)"; char str2[] = "((a*(b+c))*d)"; inTopast(str1); inTopast(str2); inToprev(str1); inToprev(str2); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/q547550831/article/details/47396893