用智能指针实现一个简单的单向链表 [英] Implementing a simple singly linked list with smart pointers

查看:34
本文介绍了用智能指针实现一个简单的单向链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用智能指针实现一个简单的单链表,这是我到目前为止所拥有的,我选择使用 C++ 的 shared_ptr,但我读到 unique_ptr 更适合这种情况,但是,我不真的不知道您将如何遍历列表(即 currentNode = currentNode->next)以到达列表的末尾,以便使用 unique_ptr 插入一个元素.这是我到目前为止的代码:

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 (i.e 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;
};

如果使用 unique_ptrs 是该程序的更好方法,您能否说明我将如何解决迭代问题?由于无法分配unique_ptrs,我将如何做代码块:

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);

使用 unique_ptrs 而不是 shared_ptrs?谢谢!

using unique_ptrs instead of shared_ptrs? Thanks!

推荐答案

您使用 std::unique_ptr 的循环可能如下所示:

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);

这篇关于用智能指针实现一个简单的单向链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆