So we were in class today and my professor said that, while iterating through a linked list you can use the ++ operator to get the next node. Here's an example linked list...
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node * next;
};
class List {
public:
List();
void append(int i);
void print();
void test();
private:
Node* front;
Node* back;
};
List::List() {
front = back = NULL;
}
void List::append(int i) {
Node *n = new Node;
n->data = i;
n->next = NULL;
if (front == NULL) {
front = back = n;
} else {
back->next = n;
back = n;
}
}
void List::print() {
cout << "printing" << endl;
for (Node *n = front; n != NULL; n = n->next) {
cout << n->data << endl;
}
}
int main() {
List l;
l.append(1);
l.append(2);
l.append(3);
l.print();
return 0;
}
The line of interest is in print().
for (Node *n = front; n != NULL; n = n->next)
He claimed you can just do n++ instead of n = n->next. I disagree. While it may work sometimes if the nodes grab memory quick enough they are grabbing contiguous memory addresses, it would fail if the addresses were not contiguous.
This lead me to wanting to over load the ++ operator to achieve the behavior he described.
I ran into some problems... n isn't a Node, it's a pointer to a Node. So we'd have to overload the operator with the pointer as an argument instead of a Node. I couldn't really see a way to do this as a member.
The other issue is, we'd have to reassign the address of this. We'd be saying this = this->next. I'm pretty sure you can't do that because this isn't an lvalue.
So does anyone have an elegant way of overloading the ++ operator so the following is valid?
for (Node *n = front; n != NULL; n++)