将链接列表插入链接列表

时间:2015-09-25 04:05:13

标签: c++ algorithm memory-management data-structures linked-list

我写了这个函数,将另一个链表插入到现有的链表中。当我打印出"这个"的值时,输出是正确的。函数中的对象。但是,当最终调用析构函数时,程序会遇到运行时错误。我认为运行时错误是由2个指针指向同一个地址引起的;因此,当一个人被取消分配时,另一个人成为悬空指针。

有没有什么方法可以将另一个链表插入到现有链表(中间)而不会导致此问题?

void List::insert(const List& otherList, const int &index)
{
    Node* insertion = head;
    int x = index;
    while (x > 0){
        insertion = insertion->next;
        x--;
    }

    if (index == 0){  //this works fine
        otherList.tail->next = insertion;
        *this = otherList;  /*I implemented a copy ctor 
                              that performs deep copy 
                              so this is also fine */
    }
    else{ // this block causes problems
        Node* tmp = insertion->next;
        insertion->next = otherList.head;
        otherList.tail->next = tmp;
    }
    cout << "after the copy\n" << (*this) << endl;
}

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

一个问题是,您不清楚对插入函数的期望。

要插入的其他列表在哪里?我认为索引应该意味着otherList的头部将成为位置索引处的节点(从零开始计数)。这也是你的代码为index = 0做的事情,但是对于index = 1,你实际上在当前元素编号1之后插入。这可以通过改变while来修复,即

while (x > 1)

另一个问题是在使用指针之前不要检查nullptr。必须修复。

第三个问题是当索引&gt;时你没有得到副本。 0

我不确定您的副本是否正常,因为您没有提供代码。

这是另一种方法(插入函数重命名为insert_list_copy_at):

class Node
{
public:
    Node() : next(nullptr) {};

    Node(const Node& other)
    {
        next = other.next;

        // Copy other members
    };

    Node* next;

    // other members
};

class List
{
public:
    Node* head;
    Node* tail;

    void insert_list_copy_at(const List& otherList, int index);
    void insert_node_at(Node* node, int index);
};

void List::insert_node_at(Node* node, int index)
{
    if (index == 0)
    {
        node->next = head;
        head=node;
        if (tail == nullptr)
        {
            tail=node;
        }
            return;
    }

    if (head == nullptr) {/*throw exception - index out of range*/};

    Node* t = head;
    while(index>1)
    {
        t = t->next;
        if (t == nullptr) {/*throw exception - index out of range*/};
    }

    // Insert node after t
    node->next = t->next;
    t->next = node;
    if (tail == t)
    {
        tail=node;
    }
}

void List::insert_list_copy_at(const List& otherList, int index)
{
    Node* t = otherList.head;
    while(t != nullptr)
    {
        // Create new node as copy of node in otherList
        Node* tmp = new Node(*t);

        // Insert in this list
        insert_node_at(tmp, index);

        // Increment index and pointer
        index++;
        t = t->next;
    }
}

BTW - 考虑使用std :: vector而不是创建自己的列表。