0
typedef struct word {
    char *str;             
    int freq;             
    struct word *right;
    struct word *left;
    } Word;



Word *root = NULL;  //global

while(pCounter != NULL){
            if(root == NULL){
                Word *x = (Word *)malloc(sizeof(Word));
                x->str = (char*)malloc(strlen(pCounter->str)+1);
                //printf("%s", node->str);
                strcpy(x->str,pCounter->str);
                x->freq = pCounter->freq;
                x->left = NULL;
                x->right = NULL;
                root = x;
                }
                else {
                    Insert(pCounter, root);
                }
            pCounter = pCounter ->pNext;
        }


void * Insert(Word *node, Word *root)
        {
            printf("inserted%s\n", node->str);
            if(root==NULL)
            {
                Word *x = (Word *)malloc(sizeof(Word));
                x->str = (char*)malloc(strlen(node->str)+1);
                //printf("%s", node->str);
                strcpy(x->str,node->str);
                x->freq = node->freq;
                x->left = NULL;
                x->right = NULL;
                return x;
                //node = root;
            }
            else if (strcmp(node->str, root->str)==0){

                root -> freq = root->freq+1;
            }
            else if (strcmp(node->str, root->str)<1){

                root->left = Insert(node,root->left);
            }
            else {
                root->right = Insert(node, root->right);    
            }

            return node;


        }

void ordered(Word *n){
            //printf("ordered");
    if(n != NULL){
        ordered(n->left);
        printf("%-30s   %5d\n", n->str, n->freq);
        ordered(n->right);
            }   
        }

我正在尝试构建一个二叉搜索树来将一个链表处理成一个有序的 bst。我可以让 root 的输出正确显示,但不能显示其他任何内容。它吐出一些垃圾,我不知道为什么。我设置了一个 printf 语句,它显示它正在插入实际的字符串。难道我做错了什么?这不是所有的代码,但我认为这已经足够人们理解我在做什么了。建议?

4

1 回答 1

0

return node; -->return root;根据 BLUEPIXY 的评论,这是正确的答案。– BLUEPIXY 2 分钟前

于 2014-12-06T22:57:34.733 回答