插入双链表中的特定位置

时间:2018-06-19 22:34:24

标签: c++ linked-list

我在此处发表了有关代码审查的帖子,该帖子可以在here中找到。有人告诉我我的insertPosition函数不会更新头或尾。当我问到有关此主张的一些问题时,我的问题充耳不闻。

功能如下:

template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData) {
    Node* current = head;
    int i = 0;
    while (current != nullptr) {
        if (i++ == pos) {
            Node* newNode = new Node;
            newNode->data = theData;
            // Let's do the wiring
            newNode->previous = current->previous;
            newNode->next = current;
            if (newNode->previous != nullptr) {  // If the node is inserted at the end
                newNode->previous->next = newNode;
            }
            current->previous = newNode;
            return;
        }
        current = current->next;
    }
}

后一种功能是否不会更新头部或尾部?如果是这样,我应该如何更改?

1 个答案:

答案 0 :(得分:2)

  

该函数是否不更新headtail

不,不是。自己看看。在其代码的任何地方都没有提到headtail,并且它也没有调用任何可能引用这些成员的类方法。

代码应如下所示:

template <class T>
void DoubleLinkedLists<T>::insertPosition(int pos, const T& theData)
{
    if (pos < 0)
        throw std::invalid_argument("pos is not a valid index");

    Node *current = head, *previous = nullptr;
    while (pos-- > 0) {
    {
        if (!current)
            throw std::invalid_argument("pos is not a valid index");

        previous = current;
        current = current->next;
    }

    Node* newNode = new Node;
    newNode->data = theData;

    // Let's do the wiring
    newNode->previous = previous;
    newNode->next = current;

    if (newNode->previous)
        newNode->previous->next = newNode;
    else
        head = newNode;

    if (newNode->next)
        newNode->next->previous = newNode;
    else
        tail = newNode;
}