Skip to content

Instantly share code, notes, and snippets.

@meshell
Created February 22, 2016 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meshell/f4ee5b573a04eb6552dd to your computer and use it in GitHub Desktop.
Save meshell/f4ee5b573a04eb6552dd to your computer and use it in GitHub Desktop.
Addaption of the Double Linked list from http://www.cprogramming.com/snippets/source-code/double-linked-list-cplusplus using C++11 smart pointers.
#ifndef DOUBLE_LINKED_LIST_H
#define DOUBLE_LINKED_LIST_H
#include <vector>
#include <memory>
#include <iostream>
template<typename T>
struct Node {
explicit Node(T val)
: value{val}
{}
~Node() {
std::cout << "Node " << value << " destroyed\n";
}
Node(const Node&) = default;
Node(Node&&) = default;
Node& operator=(const Node&) = default;
Node& operator=(Node&&) = default;
T value;
std::shared_ptr<Node> next = nullptr;
std::weak_ptr<Node> previous; // using a shared_ptr would introduce circular dependencies
};
template<typename T>
class DoubleLinkedList {
public:
void push_front (T x);
void push_back (T x);
std::vector<T> get_nodes_forward() ;
std::vector<T> get_nodes_reverse ();
private:
std::shared_ptr<Node<T>> front = nullptr;
std::shared_ptr<Node<T>> back = nullptr;
};
template<typename T>
void DoubleLinkedList<T>::push_front(T x)
{
const auto n = std::make_shared<Node<T>>(x);
if( not front) {
front = n;
back = n;
} else {
front->previous = n;
n->next = front;
front = n;
}
}
template<typename T>
void DoubleLinkedList<T>::push_back(T x)
{
const auto n = std::make_shared<Node<T>>(x);
if( not back) {
front = n;
back = n;
} else {
back->next = n;
n->previous = back;
back = n;
}
}
template<typename T>
std::vector<T> DoubleLinkedList<T>::get_nodes_forward()
{
auto temp = front;
std::vector<T> out;
while(temp) {
out.push_back(temp->value);
temp = temp->next;
}
return out;
}
template<typename T>
std::vector<T> DoubleLinkedList<T>::get_nodes_reverse()
{
auto temp = back;
std::vector<T> out;
while(temp) {
out.push_back(temp->value);
temp = temp->previous.lock();
}
return out;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment