Question

For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list.

#include <iostream>
using namespace std;

class Set {
    private:
        int num;
        Set *nextval;
        bool empty;
    public:
        Set();
        <some return type> next();
};

<some return type> Set::next() {
    Set *current;
    current = this;
    return current->next;
}

int main() {
    Set a, *b, *c;
    for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question

    // Test the next_element() iterator
    b = a.next();
    c = b->next();
    cout << "Third element of b = " << c->value() << endl;

    return 0;
}

As you can see, I need to set the pointer *b and *c to the memory address that holds the next element in the list. My question is what kind of return type would I use? I've tried putting Set and Set* in place of but get compiler errors. Any help is greatly appreciated.

Was it helpful?

Solution

Set* is correct. You are suffering from a rather silly bug in this function:

Set* Set::next() {
    Set *current;
    current = this;
    return current->next;
}

The last line should be return current->nextval. Otherwise you are trying to return a pointer to the next function... probably not what you want, ever. :-)

OTHER TIPS

luqui is correct, although your next function is overly complex, there's no reason to copy the this pointer, that's just silly. Use this instead:

Set* Set::next() {
    return nextval;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top