今天去晟鋒軟件公司機試了.一共6道題,時間爲3小時.前5道很普通,簡單.後一道的工作量有點大----直接輸多項式字符串進行運算.當時只是把二叉樹做完就沒時間了,很是不爽,就差一點了,於是下來接着做.自己隨便做着沒壓力,花了半個小時就完成了調試字符串的遞歸建樹與樹的遞歸運算.
貼上劣作代碼,算是對自己的激勵.歡迎遇到此題的同志拍磚,呵呵
//爲使算法直觀易懂,建立二叉樹時不進行數字字符轉換成相應的整數,在計算時才互相轉換,直觀但效率很低
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
//轉換函數,不能轉換小數與負數,計算步驟中不能出現負數與小數
int convert(char *p)//將數字字符轉換成相應的整數,以便進行計算
{
int A=0;
int* a=new int[strlen(p)];
for(int i=strlen(p)-1;i>=0;i--)
{
a[i]=p[i]-48;
int s=1;
for(int j=1;j<=(strlen(p)-i-1);j++)s=s*10;
A=a[i]*s+A;
}
delete[] a;
return A;
}
char* convert(int p)//將整數轉換成相應的數字字符,以便進行計算
{int s=0,c=0;
for(int a=p;a>=1;a=int(a/10))s++;
char* A=new char[s+1];
A[s]='/0';
for(double aa=(double)p/10;aa>=0.1;aa=aa/10)
{int b=aa*10-(int)aa*10;
A[s-c-1]=(char)(b+48);
c++;
}
return A;
delete[] A;
}
//二叉樹結構
struct tree
{
char data[12];
tree* nodel;
tree* noder;
};
//建立 er cha shu,並按運算優先級排序,運算時就從最底下的兩片葉子開始,此函數沒問題
//可以在建樹時進行運算,但爲了算法的可讀性,另寫一函數計算
tree * createtree(char* shi,int l,int r,tree* headl,tree* headr)
{//先提取+-,採用快速排序的二分法思想對多項式進行遞歸分解
tree* node=new tree;
node->nodel=0;
node->noder=0;
char* temp=shi;
for(temp+=r;temp>=shi+l;temp--)
{
if(*temp=='+'||*temp=='-')
{
node->data[0]=*temp;
node->data[1]=0;
if(headl!=0) headl->nodel=node;
createtree(shi,l,(int)temp-(int)shi-1,node,0);
if(headr!=0) headr->noder=node;
createtree(shi,(int)temp-(int)shi+1,r,0,node);
return node;
}
}
temp=shi;
for(temp+=r;temp>=shi+l;temp--)
{
if(*temp=='*'||*temp=='/')
{
node->data[0]=*temp;
node->data[1]=0;
if(headl!=0) headl->nodel=node;
createtree(shi,l,(int)temp-(int)shi-1,node,0);
if(headr!=0) headr->noder=node;
createtree(shi,(int)temp-(int)shi+1,r,0,node);
return node;
}
}
temp=shi;
for(temp+=r;temp>=shi+l;temp--)
{
if(*temp>='0'||*temp<='9')//ke yi bu pan duan
{
node->data[(int)temp-(int)shi-l]=*temp;
node->data[(int)temp-(int)shi-l+1]=0;
if(headl!=0) headl->nodel=node;
if(headr!=0) headr->noder=node;
return node;
}
}
}
//遍歷tree並求值,遞歸式
void count(tree* node)
{
if(node->nodel)
{
count(node->nodel);
count(node->noder);
switch(node->data[0])
{
case '+':{strcpy(node->data,convert(convert(node->nodel->data)+convert(node->noder->data)));break;}
case '-':{strcpy(node->data,convert(convert(node->nodel->data)-convert(node->noder->data)));break;}
case '*':{strcpy(node->data,convert(convert(node->nodel->data)*convert(node->noder->data)));break;}
case '/':{strcpy(node->data,convert(convert(node->nodel->data)/convert(node->noder->data)));break;}
}
}
}