写入位置c++链表时发生访问冲突

access violation writing location c++ linked list

本文关键字:访问冲突 链表 位置 c++      更新时间:2023-10-16

我正在尝试编写一个函数,该函数将指针指向头节点,然后使用递归反转节点之间的链接方式。

下面是我的函数。

void reverseRec(digits *&head){
digits *temp = head;
if(temp->next = NULL){
    head = temp;
    return;
  }
reverseRec(head->next);
digits * a = temp->next;
a->next = temp;
temp->next = NULL;
}

函数调用如下:

int main(){
    digits * head = new digits(); // pointer that points to head of the node
    head = NULL;
    insert(head, 5, 1); 
    insert(head, 6, 2);
    insert(head, 1, 3);
    insert(head, 7, 1);
    delList(head, 1);
    reverseRec(head);
}

如果有帮助的话,我试着用while循环使用一个正常的反向函数,结果很好,我的代码是这样的:

void reverse(digits *&head){
    digits * prev, * current, * next;
    current = head;
    prev = NULL;
    while(current!= NULL){
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    head = prev;
}

我是C++的新手,我遇到了很多"访问违规写入位置"错误,直到现在我都不知道它是什么(我通常会修改代码,直到它被修复,但我从来都不知道是什么原因导致的)。

很抱歉,这真的是一个新手问题,这些访问违规写入位置错误是什么?我的代码出了什么问题?

当您试图写入或读取未经程序授权的内存区域时,会发生访问冲突错误。你能告诉我这个访问违规错误是从哪里来的吗?

实际上,在IF()条件中,您的方程式Temp->Next为NULL。你可以尝试更改。。

if(temp->next = NULL)

if(!temp->next)

在main()中,更改头部分配。

head ->next= NULL;