简体   繁体   中英

Why doesn't my code work when I want to append something to be head of the linked list?

void addToHead(Node *list, Node added) 
{
    // Where NodePointer is a typedef of a pointer to a node

    (*added).next = (*list); 
    (*list) = added;        //Set list pointer back to first entry
}

For some reason, I'm having issues with this. Why doesn't it work? I thought adding a pointer to a pointer will allow me to change the address of a pointer (as I did with Node * list)

It's hard to say what you're after because I find your question unclear. I'm going to assume that Node contains a Node* next (pointer to Node) because a class or struct cannot contain a full instance of itself and therefor Node.next cannot be a Node .

First, with (*added).next = (*list); . (*list) dereferences a Node* and resolves as a Node , so I'd be surprised if assigning a Node* as a Node would compile.

Second, with (*list) = added; . This one looks more likely to compile, but it will do a shallow copy of added into the space pointed to by list .

No where in your code are you assigning an actual pointer, so I'm confused by what you mean by 'adding a pointer to a pointer'. I also don't know what you mean by 'doesn't work'. You need to explain what behavior you want to see, and what behavior you actually see.

void addToHead(Node * list, Node* added) 
{
  //Where NodePointer is a typedef of a pointer to a node

  (*added).next = list;    //you could also do added->next = list
  list = added;      //Set list pointer back to first entry
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM