引发异常:违反写入权限. newNode 是 nullptr



我刚刚回到编码领域。已经有几年了。我无法弄清楚为什么这会引发 nullptr 访问冲突。我已将其压缩为一行代码。当我尝试将我的第二个条目(newNode 的 pLast 指针(设置为 head 时,会抛出违规行为。

我正在尝试创建一个双链表,其中包含基于执行的搜索(又名 countVar(的气泡排序。任何帮助都会很棒。

#include <iostream>
#include <stdlib.h>
using namespace std;
//build class that has a private function to inc count. 
class LinkedListCount {
private:
struct CountNode {
int data;
int countVar; //Make the variable "countVar" private to protect integrity. 
CountNode* pNext = NULL;
CountNode* pLast = NULL; //Needed for bubbling back through list. 
};
//Keep track of head
CountNode* head;
CountNode* current;
CountNode* temp;

public:
//Constructor Function (Set default values for head, current, and temp) 
LinkedListCount() {
head = NULL;
current = NULL;
temp = NULL;
}
void AddNode(int dataIn) { //Addnode Function
//Create and populate list. 
CountNode* newNode = new CountNode; 
newNode->pNext = NULL; 
newNode->pLast = NULL;
newNode->data = dataIn;
temp = head;
newNode->countVar = 0;
if (temp != NULL) { //We already have data entery.
if (temp->pNext == NULL) {
newNode = temp->pNext;
newNode->pLast = head; //****THIS IS WHERE ACCESS VIOLATION OCCURES
}
//Set variables with the understanding that the head is the only data point. 
else {
current = temp->pNext; //Set it equal to head. 
}
while (current->pNext != NULL) {//This could be eliminated with keeping track of a tail. 
current = current->pNext; //Attach this to the end of the list. 
}
current->pNext = newNode; //And newMode->pNext = to Null so next time I add data I'll get to the end of the list. 
newNode->pLast = current;
}
else if (head == NULL) {
head = newNode;
}
}
};
void addNodes(LinkedListCount &DataList) { //Populates list. 
for (int i = 0; i < 20; i++) {
DataList.AddNode(i);
}
}

int main(void)
{       
addNodes(DataList);   
}
if (temp->pNext == NULL) { // temp->pNext is NULL
newNode = temp->pNext; // newNode is now NULL too
newNode->pLast = head; // attempt to use pLast of NULL
}

我已经在您的代码中放置了注释,以了解您为什么会出现访问冲突。

最新更新