2
  1. For single linklist

    1.1. This is what I saw from a tutorial, I only wrote the important part.

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

    1.2. However I just used pointer rather than double pointer, and everything works fine, I can insert the key successfully.

    sortedInsert(Node *root, int key){};
    int main(){
        Node *root = &a;
        sortedInsert(root, 4);
    }
    
  2. For binary Tree

2.1. From tutorial(double pointer)

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

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

2.2. what I did is below, and I failed to insert the key, when I checked the node after insertion, the node is still null.(single pointer)

    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);
    }

I have a few questions

1). which is right, 1.1/2.1 double pointer or 1.2/2.2 single pointer? Please explain in detail, it could be better if you can show an example, I think both of them are right.

2). Why did I insert key successfully in the linkedlist with single pointer, however I failed in the tree insertion with single pointer?

Thanks very much, I appreciate everyone's help.

hellocoding
  • 221
  • 4
  • 13

2 Answers2

1

I suspect you were lucky with your linked list test. Try inserting something at the head of the list.

To expand on that...

main() has a pointer to the head of the list which it passes by value into your version of sortedInsert(). If sortedInsert() inserts into the middle or end of the list then no problem, the head is not changed and when it returns to main() the head is the same. However, if your version of sortedInsert() has to insert a new head, fine it can do that, but how does it return the information about the new head back to main()? It can't, when it returns to main() main will still be pointing at the old head.

Passing a pointer to main()'s copy of the head pointer allows sortedInsert() to change its value if it has to.

Adam Burry
  • 1,904
  • 13
  • 20
  • Hi Adam, Can you tell me why should we use pointer to pointer rather than pointer? Pointer also set or get the value by address, so it should save all changes, right? – hellocoding Aug 27 '13 at 06:32
1

both your approaches are correct.But where you used a single pointer ,your head pointer isn't being updated.All you need to do is return the new head by writing 'return head;' at the end of your function,

SynAck
  • 427
  • 5
  • 19