C++ 如何在链表的索引处插入值?c++;分段错误

C++ 如何在链表的索引处插入值?c++;分段错误,c++,C++,我在查找链接列表中的插入内容时遇到了一些问题,因为每次我都会遇到分段错误。任何关于我应该关注什么以发现这个问题的建议都将不胜感激 bool LinkedList::InsertAtIndex(int value, int index) { if (index < 0) { return false; } LinkedListNode* tmp = new LinkedListNode(); tmp->data = value;

我在查找链接列表中的插入内容时遇到了一些问题,因为每次我都会遇到分段错误。任何关于我应该关注什么以发现这个问题的建议都将不胜感激

bool LinkedList::InsertAtIndex(int value, int index)
{
    if (index < 0)
    {
        return false;
    }
    LinkedListNode* tmp = new LinkedListNode();

    tmp->data = value;

    tmp->next_node = NULL;

    if (index == 0)
    {
        tmp->next_node = head;
        head = tmp;

        return true;
    }
    LinkedListNode* head_ref = head;
    for (int i = 0; i < index - 1; i++)
    {
        head_ref = head_ref->next_node;
        if (i == index - 1)
        {
            break;
        }
    }
    if (head_ref == NULL)
    {
        return false;
    }

    temp->next_node = head_ref->next_node;
    head_ref->next_node = temp;

    return true;
}
bool链接列表::InsertAtIndex(int值,int索引)
{
如果(指数<0)
{
返回false;
}
LinkedListNode*tmp=新LinkedListNode();
tmp->数据=值;
tmp->next_node=NULL;
如果(索引==0)
{
tmp->next_节点=头部;
水头=tmp;
返回true;
}
LinkedListNode*head\u ref=head;
对于(int i=0;inext\u节点;
如果(i==索引-1)
{
打破
}
}
if(head_ref==NULL)
{
返回false;
}
临时->下一个\u节点=头部\u参考->下一个\u节点;
head\u ref->next\u node=temp;
返回true;
}

我认为在索引0之后插入节点时会出现一些问题。我重新编写了代码片段,并试图解释这些情况

LinkedListNode* prev = head; // Locate node previous to insertion point
for (int i = 0; prev != NULL && i < index; i++)
{
    // Use prev != NULL to make sure the list isn't shorter than the
    // index.

    // Use i < index to check all of 0...index-1 to get insertion 
    // at last index right. For example, in list a,b,c insert d at
    // position 3 (zero-based counting)

    if (i + 1 == index) // First, check to see whether i meets the 
    {                   // index criteria. If yes, break out. prev
        break;          // is set to the right value.
    }
    prev = prev->next_node; // Advance prev to the next node to check
}                           // the next index value.
LinkedListNode*prev=head;//将节点定位在插入点之前
对于(int i=0;prev!=NULL&&inext_node;//将prev前进到下一个节点进行检查
}//下一个索引值。

您确定您的LinkedList中的项目数与用于插入的索引数相同吗?在0处插入是否正常工作?您可能还需要检查
head
temp
是否为
NULL
。在
head\u ref=head\u ref->next\u节点之前,还要检查
head\u ref
中的
NULL
专注于启动调试器并单步执行函数,观察下一个节点是否存在错误或空
s
中的code>无效,因为
i
最多将
索引-2
。。。