在c++中实现LinkedList时,应出现未处理的错误

Expection Unhandled Error when implementing a LinkedList in c++

本文关键字:未处理 错误 c++ 实现 LinkedList      更新时间:2023-10-16

好吧,我正试图实现LinkedList数据结构,但当我试图循环浏览我的列表(printNodes和insert函数(时,我遇到了一个错误,上面写着:";引发未处理的异常:读取访问冲突。tmpNode是0xCDCDCDCD"我觉得这与我的指示没有按照我认为的方式行事有关,但我不确定。如能提供协助,我们将不胜感激。

#include<iostream>;
using namespace std;
struct Node {
int data;
Node* next;
Node(int el) {data = el; } //constructor
Node(int el, Node* ptr) { data = el; next = ptr; } //constructor
};
class LinkedList {
public:
Node* head = NULL, * tail = NULL;
void addToHead(int el) {
head = new Node(el, head);
}
void insert(int el) {
Node* newNode = new Node(el);
if (head == nullptr) {
head = newNode;
}
else {
Node* tmpNode = head;
while (tmpNode->next != nullptr) {
tmpNode = tmpNode->next;
}tmpNode->next = newNode;
}
}
void printNodes() {
Node* tmpNode = head;
cout << tmpNode->data;
while (tmpNode->next != nullptr) {
std::cout << tmpNode->data;
tmpNode = tmpNode->next;
}
}
};
int main() {
LinkedList myList = LinkedList();
myList.insert(10);
myList.addToHead(20);
myList.insert(10);
myList.printNodes();
}

您的迭代是正确的,但printNodes函数有问题。它取消引用tmpNode而不检查null:

void printNodes() {
Node* tmpNode = head;
cout << tmpNode->data; // <-- here
while (tmpNode->next != nullptr) {
std::cout << tmpNode->data;
tmpNode = tmpNode->next;
}
}

我会将其更改为以下内容:

void printNodes() {
Node* tmpNode = head;
while (tmpNode != nullptr) {
std::cout << tmpNode->data << ", ";
tmpNode = tmpNode->next;
}
}

除此之外,正如评论中所说,如果在Node构造函数中将next成员设置为null,它应该可以正常工作。

搜索是一样的,但检查数据:

Node* findNode(int el) {
Node* tmpNode = head;
Node* ret = nullptr;
while (tmpNode != nullptr) {
if (tmpNode->data == el) {
ret = tmpNode;
break;
}
tmpNode = tmpNode->next;
}
return ret;
}

并且在main:中

Node* n = myList.findNode(10);
if (n)
std::cout << "N 10: " << n->data << "n";
n = myList.findNode(30);
if (n)
std::cout << "N 30: " << n->data << "n";
else
std::cout << "There is no N 30n";

正如@RikusHoney在评论中指出的那样,也存在内存泄漏问题。