2013-08-23 132 views
2
  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)。爲什麼我用單個指針成功地在關聯列表中插入關鍵字,但是我用單個指針插入樹失敗了?

非常感謝,我感謝大家的幫助。

回答

0

我懷疑你很幸運,你的鏈表測試。嘗試在列表的頭部插入一些東西。

爲了擴大對...

main()中有一個指針指向它經過值到您的sortedInsert版本列表的頭()。如果sortedInsert()插入到列表的中間或末尾,那麼沒有問題,頭部不會更改,並且當它返回到main()時頭部是相同的。但是,如果你的sortedInsert()版本需要插入一個新的頭部,那麼可以這樣做,但是它如何將有關新頭部的信息返回給main()?它不能,當它返回到main()時main仍然指向舊頭。

傳遞指向main()的頭指針副本的指針允許sortedInsert()在必要時更改其值。

+0

嗨,亞當,你能告訴我爲什麼我們應該使用指針而不是指針?指針也設置或獲取地址的值,所以它應該保存所有的變化,對吧? – hellocoding

0

你的方法都是正確的。但是你使用單個指針的地方,你的頭指針並沒有被更新。所有你需要做的是通過寫'return head'來返回新的頭部。在你的函數結束,