简体   繁体   中英

Implementing a simple singly linked list with smart pointers

Hi I'm trying to implement a simple singly linked list using smart pointers, here is what I have so far, I opted with using C++'s shared_ptr but I read that a unique_ptr would be more appropriate for this case but, I don't really know how you would iterate over the list (ie currentNode = currentNode->next) to get to the end of the list in order to insert an element using a unique_ptr. Here is the code I have so far:

template <typename T>
class LinkedList;

template <typename T>
class ListNode
{
public:
    ListNode() : _data(T()) {}
    explicit ListNode(const T& value) : _data(value) {}

    friend class LinkedList < T > ;
private:
    T _data;
    shared_ptr<ListNode<T>> _next;
};

template <typename T>
class LinkedList
{
public:
    void push_back(const T& value)
    {
        if (_root)
        {
            shared_ptr<ListNode<T>> currentNode(_root);

            while (currentNode->_next != nullptr)
            {
                currentNode = currentNode->_next;
            }

            currentNode->_next = make_shared<ListNode<T>>(value);
        }
        else
        {
            // If the list is completely empty,
            // construct a new root (first element)
            _root = make_shared<ListNode<T>>(value);
        }
    }

    void print() const
    {
        shared_ptr<ListNode<T>> currentNode(_root);

        while (currentNode != nullptr)
        {
            cout << currentNode->_data << " ";
            currentNode = currentNode->_next;
        }

        cout << endl;
    }
private:
    shared_ptr<ListNode<T>> _root;
};

If using unique_ptrs are the better way to go for this program, could you illustrate how I would get past the iterating problem? Since unique_ptrs can't be assigned, how would I do the code block:

shared_ptr<ListNode<T>> currentNode(_root);

while (currentNode->_next != nullptr)
{
    currentNode = currentNode->_next;
}

currentNode->_next = make_shared<ListNode<T>>(value);

using unique_ptrs instead of shared_ptrs? Thanks!

Your loop with std::unique_ptr may look like:

// Iteration doesn't own resource, so no unique_ptr here.
ListNode<T>* currentNode(_root.get());

while (currentNode->_next != nullptr)
{
    currentNode = currentNode->_next.get();
}

currentNode->_next = make_unique<ListNode<T>>(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM