Reputation: 2241
I am writing a linked list for my homework assignment and I need to implement begin() and end() for my program's requirement.
Begin() is fairly easy
Node* List::begin(){return head;}
How should I implement end()?
Upvotes: 2
Views: 799
Reputation: 32500
You can return a NULL
pointer, or if you have a custom tail
node, return that. If it's a circular doubly-linked list, you can return the sentinel node.
Keep in mind that the proper way to check for the end of the list is to call List::end()
, so if you've properly setup your List
class, then it doesn't exactly matter what you return, as long as
Node* node = mylist.begin();
while (node != mylist.end()) { /*... loop */ }
works and you exit the while
-loop when you reach the end of the list. So that main thing is that List::end()
needs to return something unique that you will never encounter if you're traversing the middle of the list.
Upvotes: 3