[cpp] doubly_linked_list_node.hpp
Viewer
- #ifndef _DOUBLY_LINKED_LIST_NODE_HPP_
- #define _DOUBLY_LINKED_LIST_NODE_HPP_
- #include <iostream>
- #include <memory>
- // The DoublyLinkedListNode class encapsulates a node in a doubly-linked
- // list.
- template <class T>
- class DoublyLinkedListNode {
- public:
- // The constructor, creating a node with the given data and given previous
- // and next nodes.
- DoublyLinkedListNode(
- DoublyLinkedListNode<T>* prev, const T& element,
- std::unique_ptr<DoublyLinkedListNode<T>> next)
- : prev_(prev), element_(element), next_(std::move(next)) {}
- // Delete the default constructor.
- //
- // It isn't useful to create a node without an element and without a
- // previous and next node.
- DoublyLinkedListNode() = delete;
- // Delete the copy constructor.
- //
- // It doesn't make sense to have two nodes in the same spot of the list.
- DoublyLinkedListNode(const DoublyLinkedListNode<T>& other) = delete;
- // Delete the copy assignment constructor.
- //
- // It doesn't make sense to have two nodes in the same spot of the list.
- DoublyLinkedListNode& operator=(
- const DoublyLinkedListNode<T>& other) = delete;
- // Returns the data stored in this node.
- T element() const {
- return element_;
- }
- // Sets the data stored in this node.
- void set_element(const T& element) const {
- element_ = element;
- }
- // Returns a smart pointer reference to the next node.
- std::unique_ptr<DoublyLinkedListNode<T>>& next_smart() {
- return next_;
- }
- // Returns a raw (unowned) pointer to the next node.
- DoublyLinkedListNode<T>* const next() const {
- return next_.get();
- }
- // Returns a raw (unowned) pointer to the previous node.
- DoublyLinkedListNode<T>* const prev() const {
- return prev_;
- }
- // Sets the next node.
- void set_next(std::unique_ptr<DoublyLinkedListNode<T>> next) {
- next_ = std::move(next);
- }
- // Sets the previous node.
- void set_prev(DoublyLinkedListNode<T>* prev) {
- prev_ = prev;
- }
- // Prints a representation of this node to standard output.
- void print() {
- std::cout << "<&this = " << this;
- if (prev_ == nullptr) {
- std::cout << ", prev = nullptr";
- }
- else {
- std::cout << ", prev = " << prev();
- }
- std::cout << ", element = " << element();
- if (next_ == nullptr) {
- std::cout << ", next = nullptr";
- }
- else {
- std::cout << ", next = " << next();
- }
- std::cout << ">, ";
- }
- private:
- // A raw (unowned) pointer to the previous node in the linked list.
- //
- // If there is no previous node, this will be nullptr.
- DoublyLinkedListNode<T>* prev_;
- // The data element this node holds.
- T element_;
- // A pointer to the next node in the linked list.
- //
- // If there is no next node, this will be nullptr.
- std::unique_ptr<DoublyLinkedListNode<T>> next_;
- };
- #endif
Editor
You can edit this paste and save as new:
File Description
- doubly_linked_list_node.hpp
- Paste Code
- 25 Sep-2021
- 3.05 Kb
You can Share it:
Latest Code Pastes