在链接列表c ++的索引处插入元素

时间:2015-09-17 06:49:51

标签: c++ linked-list segmentation-fault

我试图在索引位置的链表中插入新元素。为此,我考虑使用新数据创建一个新节点,并使索引(n-1)的前一个节点指向新节点。然后,我想删除(n-1)之前指向的节点(whew)。

bool LinkedList::InsertAtIndex(int value, int index) 
{
    LinkedListNode* temp = new LinkedListNode();

    temp->data = value;
    temp->next_node = NULL;

    if (index == 1) 
    {
        temp->next_node = head;
        head = temp;

        return true;
    } 

    LinkedListNode* temp2 = head;

    for (int i = 0; i<index-2; i++) 
    {
        temp2 = temp2->next_node;
    }

    temp->next_node = temp2->next_node;

    temp2->next_node = temp;

    delete [] temp;

    return true;
}

格式化有点麻烦,但它编译。但是在运行时会出现分段错误。我假设我的逻辑是错误的,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

我猜是

delete [] temp;

temp不是数组,所以你应该通过

释放内存
delete temp;

此外,我建议使用智能指针而不是原始指针(查找std::shared_ptr或Wikipedia开始:https://en.wikipedia.org/wiki/Smart_pointer

相关问题