-1

Say I have a linked list node class

class node {
    private: 
        node *next_node;
    public:
        node *next() const;
};

node *node::next() const {
    return next_node;
}

Does next() return a node **next_node or node *next_node. Also what is the significance of either in implementing the list class functions (ie. insert, remove, find)?

The reason I would think it returns a **next_node is because next_node is already a pointer and returning it in a function as a pointer would make it a pointer to a pointer. I read in other questions such as: Linked list head double pointer passing that double pointers also work in list operations so I was a bit confused.

3
  • 5
    I suggest that you do your homework yourself Commented Apr 13, 2012 at 16:14
  • 4
    Can you explain, in your own words, why you think this might return a node**? Commented Apr 13, 2012 at 16:20
  • Sorry, I haven't been in school for a couple months. I wanted to brush up on programming skills and pointers is one of my weak points. I understand if this question can come off as a homework question. Commented Apr 13, 2012 at 16:31

2 Answers 2

0

The node::next() function as implemented is returning a copy of the next_node member variable. Both next_node and this copy point to the same node instance but they are otherwise independent of each other.

Here is some rather bad ASCII art that tries to demonstrate their relationship

next_node ----> [node instance]
                ^
the copy ------/
Sign up to request clarification or add additional context in comments.

3 Comments

What would be the difference if the function was implemented as node node::next() const { return next_node; } Would this just simply return the next_node by value and be the same as: node *node::next() const { return &next_node; }
@rcell that actually won't compile. You need to write node node::next() const { return *next_node; }. This would return a shallow copy of the next_node value.
I would've thought that return *next_node; would have been the same as *node::next. By my understanding then the latter is return what is called a deep copy?
0

As the declaration says, it returns a pointer to the next node, of type node*.

It's used to advance through the list; for example:

for (node * n = list.head(); n; n = n->next()) {
    // Process node n
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.