【发布时间】:2014-11-16 19:04:09
【问题描述】:
程序应该读取一个 txt,按字母顺序存储所有单词并按顺序打印它们,以及单词在 txt 中出现的次数。
问题似乎出在 Insert 方法中,因为它从不打印 TEST,因此 pAux 似乎出于某种原因始终为 NULL。正因为如此,Print 方法在他的第一次调用中返回。
我做错了什么?
树.h
#ifndef TREE_H_
#define TREE_H_
typedef struct Item{
char* key;
int no;
} TItem;
typedef struct No{
TItem item;
struct No* pLeft;
struct No* pRight;
} TNo;
void TTree_Insert (TNo**, char[]);
void TTree_Print (TNo*);
#endif
树.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
TNo* TNo_Create (char* c){
TNo* pNo = malloc(sizeof(TNo));
pNo->item.key = malloc(sizeof(char)*strlen(c));
strcpy(pNo->item.key, c);
pNo->item.no = 1;
pNo->pLeft = NULL;
pNo->pRight = NULL;
return pNo;
}
void TTree_Insert (TNo** pRoot, char word[80]){
char* c = malloc(sizeof(char)*strlen(word));
strcpy(c, word);
TNo** pAux;
pAux = pRoot;
while (*pAux != NULL){
if (strcmp(c, (*pAux)->item.key) < 0) pAux = &((*pAux)->pLeft);
else if (strcmp(c, (*pAux)->item.key) > 0) pAux = &((*pAux)->pRight);
else{
(*pAux)->item.no++;
return;
}
}
*pAux = TNo_Create(c);
return;
}
void TTree_Print (TNo *p){
if (p == NULL) return;
TTree_Print (p->pLeft);
printf("%s - %d", p->item.key, p->item.no);
TTree_Print (p->pRight);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "tree.h"
int main(){
TNo* pRoot = NULL;
FILE* txt = fopen("Loremipsum.txt", "r");
char aux[80];
int c, x = 0;
while ((c = fgetc(txt)) != EOF){
while (!(isalpha((char)c))) c = fgetc(txt);
while (isalpha((char)c)) {
if (isupper((char)c)) c = c+32;
if (islower((char)c)) aux[x++] = (char)c;
c = fgetc(txt);
}
aux[x] = '\0';
TTree_Insert(&pRoot, aux);
x = 0;
aux[0] = '\0';
}
TTree_Print(pRoot);
fclose(txt);
return 0;
}
【问题讨论】:
-
您永远不会更改 pRoot 的值。 TTree_Insert 只是获取 pRoot 的值。您将新节点的地址分配给 pAUx,但在函数返回时将其丢弃。
-
如果您从 main 修改变量,则需要将该变量引用传递给函数
-
你通过值传递
pRoot。
标签: c binary-search-tree