【问题标题】:pointer vs double pointer for Linked List and Binary Tree链接列表和二叉树的指针与双指针
【发布时间】:2013-08-26 04:49:31
【问题描述】:
  1. 对于单链表

    1.1。这是我从教程中看到的,我只写了重要的部分。

    sortedInsert(Node **root, int key){};
    int main(){
        Node *root = &a;
        sortedInsert(&root, 4);
    }
    

    1.2。但是我只是使用指针而不是双指针,一切正常,我可以成功插入密钥。

    sortedInsert(Node *root, int key){};
    int main(){
        Node *root = &a;
        sortedInsert(root, 4);
    }
    
  2. 对于二叉树

2.1。来自教程(双指针)

    void insert_Tree(Tree **root, int key){
    }

    int main(){  
        Tree *root = NULL;
        insert_Tree(&root, 10);
    }

2.2。我所做的是下面,我没有插入密钥,当我插入后检查节点时,节点仍然为空。(单指针)

    void insert_Tree(Tree *root, int key){
        if(root == NULL){
        root = (Tree *)malloc(sizeof(Tree));
        root->val = key;
        root->left = NULL;
        root->right = NULL;
        cout<<"insert data "<<key<<endl;
    }else if(key< root->val){
        insert_Tree(root->left, key);
        cout<<"go left"<<endl;
    }else{
        insert_Tree(root->right, key);
        cout<<"go right"<<endl;
    }
    }
    int main(){  
        Tree *root = NULL;
        insert_Tree(root, 10);
    }

我有几个问题

1)。哪个是正确的,1.1/2.1 双指针或 1.2/2.2 单指针?请详细解释一下,如果能举个例子就更好了,我觉得两个都对。

2)。为什么单指针链表插入key成功,单指针树插入失败?

非常感谢,感谢大家的帮助。

【问题讨论】:

    标签: pointers linked-list binary-tree insertion double-pointer


    【解决方案1】:

    您的两种方法都是正确的。但是在您使用单个指针的地方,您的头指针没有被更新。您需要做的就是通过编写“返回头”来返回新头;在函数结束时,

    【讨论】:

      【解决方案2】:

      我怀疑您的链表测试很幸运。尝试在列表的头部插入一些东西。

      进一步扩展...

      main() 有一个指向列表头部的指针,它通过值传递给您的 sortedInsert() 版本。如果 sortedInsert() 插入到列表的中间或末尾,那么没问题,头部不会改变,当它返回到 main() 时,头部是相同的。然而,如果你的 sortedInsert() 版本必须插入一个新的 head,它可以这样做,但是它如何将关于新 head 的信息返回给 main()?它不能,当它返回 main() 时,main 仍然会指向旧的头。

      将指针传递给 main() 的头指针副本允许 sortedInsert() 在必要时更改其值。

      【讨论】:

      • 嗨亚当,你能告诉我为什么我们应该使用指针而不是指针吗?指针也可以通过地址设置或获取值,所以它应该保存所有更改,对吧?
      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多