Skip to content

Instantly share code, notes, and snippets.

@AlexBolotsin
Last active July 13, 2017 20:18
Show Gist options
  • Save AlexBolotsin/12f580a3ee877dfb0c61124c0f96438f to your computer and use it in GitHub Desktop.
Save AlexBolotsin/12f580a3ee877dfb0c61124c0f96438f to your computer and use it in GitHub Desktop.
#include <string>
#include <iostream>
template <typename T>
class ListNode
{
ListNode* _next = nullptr;
T _value;
public:
ListNode(T value) : _value(value) {}
void SetNext(ListNode* node) {
_next = node;
}
ListNode* GetNext() const { return _next; }
std::string GetValue() {
return _value;
}
class Iterator
{
public:
Iterator(ListNode* ptr) : ptr_(ptr) { }
Iterator operator++() { Iterator i = *this; ptr_ = ptr_->GetNext(); return i; }
ListNode& operator*() { return *ptr_; }
ListNode* operator->() { return ptr_; }
bool operator==(const Iterator& rhs) { return ptr_ == rhs.ptr_; }
bool operator!=(const Iterator& rhs) { return ptr_ != rhs.ptr_; }
private:
ListNode* ptr_;
};
Iterator begin() { return Iterator(this); }
Iterator end() { return Iterator(nullptr); }
};
int main(int argc, char** argv)
{
ListNode<std::string> node("I've");
node.SetNext(new ListNode<std::string>("got the"));
node.GetNext()->SetNext(new ListNode<std::string>("power"));
for (auto itr : node)
std::cout << itr.GetValue() << " ";
std::cout << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment