騰訊技術(shù)類校園招聘筆試試題及答案(4)
二. 填空題(共40分)
本程序從正文文件text.in讀入一篇英文短文,統(tǒng)計(jì)該短文中不同單詞和它的出現(xiàn)次數(shù),并按詞典編輯順序?qū)卧~及它的出現(xiàn)次數(shù)輸出到正文文件word.out中.
程序用一棵有序二叉樹存儲(chǔ)這些單詞及其出現(xiàn)的次數(shù),一邊讀入一邊建立.然后中序遍歷該二叉樹,將遍歷經(jīng)過的二叉樹上的節(jié)點(diǎn)的內(nèi)容輸出.
程序中的外部函數(shù)
int getword(FILE* pFile,char* pszWordBuffer,int nBufferLen);
從與pFile所對應(yīng)的文件中讀取單詞置入pszWordBuffer,并返回1;若單詞遇文件尾,已無單詞可讀時(shí),則返回0.
#include
#include
#include
#include
#define SOURCE_FILE "text.in"
#define OUTPUT_FILE "word.out"
#define MAX_WORD_LEN 128
typedef struct treenode
{
char szWord[MAX_WORD_LEN];
int nCount;
struct treenode* pLeft;
struct treenode* pRight;
}BNODE;
int getword(FILE* pFile,char* pasWordBuffer,int nBufferLen);
void binary_tree(BNODE** ppNode,char* pszWord)
{
if(ppNode != NULL && pszWord != NULL)
{
BNODE* pCurrentNode = NULL;
BNODE* pMemoNode = NULL;
int nStrCmpRes=0;
____(1)_____;pCurrentNode=*ppNode
while(pCurrentNode)
{
/*尋找插入位置*/
nStrCmpRes = strcmp(pszWord, ___(2)___ );pCurrentNode->nCount
if(!nStrCmpRes)
{
___(3)___; pCurrentNode->nCount++
return;
}
else
{
___(4)___; pMemoNode=pCurrentNode
pCurrentNode = nStrCmpRes>0? pCurrentNode->pRight : pCurrentNode->pLeft;
}
}
}
pCurrent=new BNODE;
if(pCurrentNode != NULL)
{
memset(pCurrentNode,0,sizeof(BNODE));
strncpy(pCurrentNode->szWord,pszWord,MAX_WORD_LEN-1);
pCurrentNode->nCount=1;
}
if(pMemoNode==NULL)
{
___(5)___; *ppNode= pCurrentNode
}
else if(nStrCmpRes>0)
{
pMemoNode->pRight=pCurrentNode;
}
else
{
pMemoNode->pLeft=pCurrentNode;
}
}
void midorder(FILE* pFile,BNODE* pNode)
{
if(___(6)___) return;!pNode||!pFile
midorder(pFile,pNode->pLeft);
fprintf(pFile,"%s %d\n",pNode->szWord,pNode->nCount);
midorder(pFile,pNode->pRight);
}
void main()
{
FILE* pFile=NULL;
BNODE* pRootNode=NULL;
char szWord[MAX_WORD_LEN]={0};
pFile=fopen(SOURCE_FILE,"r");
if(pFile==NULL)
{
printf("Can't open file %s\n",SOURCE_FILE);
return;
}
while(getword(pFile,szWord,MAX_WORD_LEN)==1)
{
binary_tree(___(7)___);// pRootNode,szWord
}
fclose(pFile);
pFile=fopen(OUTPUT_FILE,"w");
midorder(pFile,pRootNode);
fclose(pFile);