keep track of pointers in double link list?

I am trying program a doubled linked list using a struct which consist of the node

1
2
3
4
5
struct node{
    int value;
    node* right;
    node* left;
};


and a class which handles the double linked list.

1
2
3
4
5
6
7
class tree{
public:
    tree(int);
    node *a;
    node *head;
    void insert(int);
};


As it can be seen from my class, I am quite having a hard time figuring out how the insert function should. My problem is how I keep updating the pointers to the right position.

I kinda have an idea how i should make the insert function , but updating the pointers seems a bit complex..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
void tree::insert(int i){

    node* temp = root;

    if (i < root->value) {
        while (/*check value of leftvalue pointer  != null*/) {
            //update leftvalue pointer with next
            if (i > /*leftvalue*/) {
                //create a right node.
            }
        }
    }else{

        while (/*check value of rightvalue pointer  != null*/) {
            //update rightvalue pointer with next
            if (i> /*rightvalue*/) {
                //create a left node.
            }
    }
    
        
    if (i > root->value) {
        while (/*check value of leftvalue pointer  != null*/) {
                //update leftvalue pointer with next
                if (i> /*leftvalue*/) {
                    //create a right node.
                }
        }
    }else{
            
        while (/*check value of rightvalue pointer  != null*/) {
                //update rightvalue pointer with next
                if (i> /*rightvalue*/) {
                    //create a left node.
                }
    }
    
    
    
    
}


any idea on how i should update the pointers??
Last edited on
I would maybe use a recursive insert instead. Something like this (I haven't tested this tho)

1
2
3
4
5
6
7
8
9
10
11
12
13
void node::insert(int i){
    if (i < node->value) {
        if (left)
            left->insert(i);
        else
            left = new Node(i);
    } else (i > node->value) {
        if (right)
            right->insert(i);
        else
            right = new Node(i);
    }
}


and then when you want to insert an int into the tree, you just insert it in the root-node.
Topic archived. No new replies allowed.