Search code examples
c++arrayspointerslinked-listskip-lists

How do I use an array of pointers in main?


I tried asking my question but I don't appear to be asking it correctly and I have been stuck for 2 months now. (which is sad)

For reference only: I built a linked list from nodes:

struct node  {
int number;
node *next;  }; 

To link these in main I used -> to assign values

void insertAsFirstElement(node *&head, node *&tail, int number){
node *temp = new node; 
temp->number = number;
temp->next = NULL; 
head = temp;
tail = temp; }

Now I am trying to make a skiplist, which should have the same structure as my original node except the node* next should be an array of pointers of type node.

struct node {
int number;
node *next[3];
};

I am getting confused on how to have an array of node pointers. I notice they tend to look like this: node **next and then declared to have memory allocated dynamically. I just want my arrays to be of size 4. So [3].

My problem is how can I create new nodes with the array of node pointers in main() and put something in the first slot of the nodes array?

This does not work for putting things in the array but it does work for putting in the number.

void insertAsFirstElement(node *&head, node *&tail, int number){

node *temp = new node; 
temp->number = number;
cout<<temp->number<<endl;
temp->next[0] = tail; 
cout<<temp->next[0]<<endl;
head->next[0] = temp;
cout<<head->next[0]<<endl;
}

Please help me.


Solution

  • The -> operator is a shorthand.

    Without the -> operator, you would write

    (*var).prop;
    

    With the -> operator, you write:

    var->prop;
    

    Thus, to store a node in the first position of the list, you write:

    void StoreNode(node *node){
        node *temp = new node;
        temp->next[0]=node;
    }
    

    And to retrieve data from a node in the list, you can write:

    temp->next[0]->number
    

    which is the same as writing

    (*temp).next[0]->number
    

    which is the same as writing

    ( *((*temp).next[0]) ).number
    

    This line of your code seems a little confused:

    void insertAsFirstElement(node *&head, node *&tail, int number){
    

    Remember, you are just passing your function the address of a node. Therefore, all you need is

    void insertAsFirstElement(node *head, node *tail, int number){
    

    Inside the function itself, you will have to find the correct location in the list, that is when you get into the ** notations.