Skip to content

Instantly share code, notes, and snippets.

@TheBuzzSaw
Created December 30, 2015 21:42
Show Gist options
  • Select an option

  • Save TheBuzzSaw/84f9c7f0482c520a92a6 to your computer and use it in GitHub Desktop.

Select an option

Save TheBuzzSaw/84f9c7f0482c520a92a6 to your computer and use it in GitHub Desktop.
Singly linked list plus reversal
#include <iostream>
#include <memory>
using namespace std;
template<class T> struct Node
{
unique_ptr<Node<T>> nextNode;
T value;
};
template<class T> class ForwardList
{
typedef unique_ptr<Node<T>> Pointer;
Pointer _head;
public:
ForwardList() = default;
ForwardList(const ForwardList&) = delete;
ForwardList(ForwardList&&) = default;
~ForwardList() = default;
ForwardList& operator=(const ForwardList&) = delete;
ForwardList& operator=(ForwardList&&) = default;
ForwardList& AddFront(T value)
{
Pointer head(new Node<T>{move(_head), move(value)});
_head = move(head);
return *this;
}
ForwardList& AddBack(T value)
{
auto last = &_head;
while (auto p = last->get()) last = &p->nextNode;
last->reset(new Node<T>{nullptr, move(value)});
return *this;
}
ForwardList& Reverse()
{
auto oldHead = move(_head);
while (auto p = oldHead.get())
{
auto next = move(p->nextNode);
p->nextNode = move(_head);
_head = move(oldHead);
oldHead = move(next);
}
return *this;
}
ostream& Write(ostream& stream)
{
stream << (void*)this;
for (auto p = _head.get(); p; p = p->nextNode.get())
stream << ' ' << p->value;
return stream;
}
};
int main(int argc, char** argv)
{
ForwardList<int> values;
values
.AddFront(1)
.AddFront(3)
.AddBack(5)
.AddFront(8);
values.Write(cout) << endl;
values.Reverse();
values.Write(cout) << endl;
values = move(values);
auto values2 = move(values);
values2.Write(cout) << endl;
values.Write(cout) << endl;
cout << "fin" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment