-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.

Community
  • 1
  • 1
rcell
  • 671
  • 1
  • 10
  • 17
  • 5
    I suggest that you do your homework yourself – David Heffernan Apr 13 '12 at 16:14
  • 4
    Can you explain, in your own words, why you think this might return a `node**`? – Mr Lister Apr 13 '12 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. – rcell Apr 13 '12 at 16:31

2 Answers2

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 ------/
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 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 Apr 13 '12 at 16:30
  • @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. – JaredPar Apr 13 '12 at 16:33
  • 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? – rcell Apr 13 '12 at 16:44
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
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644