Q1:編寫一個函數將一般算術表達式轉化爲逆波蘭表達式。
假設表達式是以字符的形式由鍵盤輸入(簡單起見,設算術表達式中的參加運算的數只有一位數字)。
字符數組str:算術表達式
字符數組exp:逆波蘭表達式
字符數組stack:棧
方法如下:
1,若C爲數字 -> 將C依次存入數組exp中;
2,若C爲左括號"(" -> 將此括號壓入棧;
3,若C爲右括號")" -> 將棧stack中左括號"("以前的字符依次彈出並存入數組exp中,將"("彈出;
4,若C爲"+"或"-" -> 將棧stack中"("以前的所有字符號依次彈出並存入數組exp中,然後將C壓入棧stack中;
5,若C爲"*"或"/" -> 將當前棧stack中棧頂連續的"*"或"/"彈出並存入數組exp中,然後將C壓入棧stack中;
6,若C爲"#" -> 將棧所有運算符彈出並存入數組exp中,符號然後將C壓入數組exp中,最後轉換的逆波蘭表達式在exp中.
My View:
1,波蘭式:二叉樹前綴表示;逆波蘭式:二叉樹後綴表示(在數據結構中有具體解釋)
2,C的判斷主要是根據符號運算的優先級,棧中彈出的都是比C優先級高或相等的.比如:C爲"+",則必須彈出"+","-","*","/".
CODE:
// trans.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define Maxsize 100/*Maxsize爲算術表達式中最多字符個數*/
void trans()
{
char str[Maxsize];//存儲原算術表達式
char exp[Maxsize];//存儲轉換後的波蘭表達式
char stack[Maxsize];//作爲棧使用
char ch;
int i,j,t,top=0;//t作爲exp下標,top作爲stack下標,i作爲str下標
i=0;//獲取用戶輸入的表達式
do
{
i++;
scanf("%c",&str[i]);
}while((str[i]!='#')&&(i<Maxsize));
t=0;i=0;
ch=str[i];i++;
while(ch!='#')
{
if((ch>='0')&&(ch<='9'))//判定爲數字
{
exp[t]=ch;t++;
}else
if(ch=='(')//判定爲左括號
{
top++;
stack[top]=ch;
}else
if(ch==')')//判定爲右括號
{
while(stack[top]!='(')
{
exp[t]=stack[top];
top--;
t++;
}
top--;//將左括號彈出
}else
if((ch=='+')||(ch=='-'))//判定爲加減號
{
while((top!=0) && (stack[top]!='('))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}else
if((ch=='*')||(ch=='/'))//判定爲乘除
{
while((stack[top]=='*')||(stack[top]=='/'))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}
ch=str[i];//繼續判斷字符
i++;
}
while(top!=0)
{
exp[t]=stack[top];
t++;
top--;
}
exp[t]='#';
for(j=0;j<=t;j++)
printf("%c",exp[j]);
printf(" ");
}
void main()
{
trans();
}
//
#include "stdafx.h"
#define Maxsize 100/*Maxsize爲算術表達式中最多字符個數*/
void trans()
{
char str[Maxsize];//存儲原算術表達式
char exp[Maxsize];//存儲轉換後的波蘭表達式
char stack[Maxsize];//作爲棧使用
char ch;
int i,j,t,top=0;//t作爲exp下標,top作爲stack下標,i作爲str下標
i=0;//獲取用戶輸入的表達式
do
{
i++;
scanf("%c",&str[i]);
}while((str[i]!='#')&&(i<Maxsize));
t=0;i=0;
ch=str[i];i++;
while(ch!='#')
{
if((ch>='0')&&(ch<='9'))//判定爲數字
{
exp[t]=ch;t++;
}else
if(ch=='(')//判定爲左括號
{
top++;
stack[top]=ch;
}else
if(ch==')')//判定爲右括號
{
while(stack[top]!='(')
{
exp[t]=stack[top];
top--;
t++;
}
top--;//將左括號彈出
}else
if((ch=='+')||(ch=='-'))//判定爲加減號
{
while((top!=0) && (stack[top]!='('))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}else
if((ch=='*')||(ch=='/'))//判定爲乘除
{
while((stack[top]=='*')||(stack[top]=='/'))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}
ch=str[i];//繼續判斷字符
i++;
}
while(top!=0)
{
exp[t]=stack[top];
t++;
top--;
}
exp[t]='#';
for(j=0;j<=t;j++)
printf("%c",exp[j]);
printf(" ");
}
void main()
{
trans();
}
RUN:
測試數據:(1+2)*((3-4)/5)#
輸出結果:12+34-5/*#
已更正錯誤!!!!!!!!!!!!!
閃……