我之前有个困惑,我把这个困惑粘贴一下吧:

我的困惑就是在creatTree函数中,参数是(LTNode &T),也就是说是struct node**型指针,但是在递归中,也就是在creatTree(T->firstchild)中,T->firstchild应该是struct node*型指针,为什么依然可以运行,且运行正确?
printfTree()函数也是一样,我就不再多写了
而在main()函数中,我也只创建了LTNode T;在调用的时候直接写T=creatTree(T);困惑在这有一个了,参数不是LTNode &T吗?为什么直接用creatTree(T)行?而用creatTree(&T)不行,而且还报错,说cannot convert parameter 1 from 'struct node ** ' to 'struct node *& '
        A reference that is not to 'const' cannot be bound to a non-lvalue
哪位高手帮我分析一下,我觉得我可能说错了,应为程序可以正确运行,但是我又不知到错在哪里?求解释...

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
        char name;
        struct node *firstchild,*nextbrother;
}TNode,*LTNode;

int n=1;
int i;

LTNode creatTree(LTNode &T){
        char c;
        printf("第%d个树元素",n);
        scanf("%c",&c);
        getchar();
        if(c=='*'){
                n--;
                T=NULL;
        }
        else{
                T=(LTNode)malloc(sizeof(TNode));
                T->name=c;
                n++;
                printf("输入成功\n");
                printf("%c的左孩子:",T->name);
                creatTree(T->firstchild);
                printf("%c的右孩子:",T->name);
                creatTree(T->nextbrother);
        }
        return T;
}

void printfTree(LTNode &T){
        if(T){
                printf("%c",T->name);
                printfTree(T->firstchild);
                printfTree(T->nextbrother);
        }
}

int main(){
        LTNode T;
        T=NULL;
        T=creatTree(T);
        printf("我们可以输出了吗?\n");
        getchar();
        printfTree(T);
        printf("\n");
        return 0;
}

一直没有得到解决,终于在今天编程的时候,我因为在创建线索二叉树,我创建了一个栈,用C语言编程的,用了stack这个词,也就是stack S;然后再引用它结构体里面的变量时,突然出现了C++的形式,使用了‘.’符号出现了很多方法。。。于是我再输入class的C++关键词。尽然在C语言里面出现蓝色了。这才让我恍然大悟啊。。

原来那书里面给得代码是伪代码,成了C语言为主,C++为辅的方式写算法。用‘&’是C++里面的引用,不是C语言里面的给地址符号,用这个符号只是为了更简洁。。。害得我这么多天一直不懂,直接照搬用了好几次。

太让找恨了,也不说明一下那个地方,误导了那么多人。。。

如果纯用C语言的话,我的写法是这样:

typedef char datatype;

typedef struct node{

  datatype data;

  struct node *lchild,*rchild;

}binnode;

typedef binnode *bintree;

void creatbintree(bintree *t){// 申明*t是指针的指针,指向bintree型指针

  char ch;

  scanf("%c%*c",&ch);

  if(ch=='*')*t=NULL;

  else{

    *t=(binnode*)malloc(sizeof(binnode));

    (*t)->data=ch;

    createbintree(&(*t)->lchild);//用*号从指针的指针里,得到bintree型指针,指向数据里的lchild,然后再用&给出地址进行递归。

    createbintree(&(*t)->rchild);

  }

}

班门弄斧,与大家分享,有错误希望得到指出,谢谢。

posted on 2013-06-03 17:31  阿宇哥哥  阅读(1058)  评论(0)    收藏  举报