![](/img/trans.png)
[英]Process returned -1073741819 (0xC0000005) in code::blocks c++
[英](C++)Process returned -1073741819 (0xC0000005) when working with a linked list, but the algorithm works
该程序的目标是从列表中删除任何大于下一个元素的元素。 我已经设法让这个程序执行这个任务,但是它在这样做之后立即崩溃并且之后不打印列表,输出一个 0xC0000005 错误代码。
#include <iostream>
using namespace std;
class List{
struct node{
int data;
node* next;
};
typedef struct node* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
public:
List()
{
head=NULL;
curr=NULL;
temp=NULL;
}
void AddNode(int addData)
{
nodePtr n = new node;
n->next = NULL;
n->data = addData;
if(head != NULL) {
curr = head;
while(curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else
{
head = n;
}
};
void DeleteNode(int delData)
{
nodePtr delPtr = NULL;
temp = head;
curr = head;
while(curr != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if(curr == NULL) {
cout << delData << " is not in the list" << endl;
delete delPtr;
}
else {
delPtr = curr;
curr = curr->next;
temp->next = curr;
if(delPtr == head) {
head = head->next;
temp = NULL;
}
delete delPtr;
cout << delData << " was removed from the list" << endl;
}
};
void PrintList()
{ cout << "List: " << endl;
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
void toss()
{
curr = head;
while (curr != NULL) {
if(curr->data>curr->next->data){
DeleteNode(curr->data);
curr = head;
}
else curr = curr->next;
if(curr == NULL) break;
}
}
};
int main() {
List list;
int i;
cout << "Input list values, stop input by inputting 0: " << endl;
cin >> i;
while(i != 0){
list.AddNode(i);
cin >> i; // 18 9 3 4 0
}
list.PrintList(); // 18 9 3 4
list.toss(); // tosses 18 and 9
list.PrintList(); // should output 3 4
};
这是代码底部注释中的测试示例,它显示删除了正确的元素,但第二次没有打印出列表。
Input list values, stop input by inputting 0:
18
9
3
4
0
List:
18
9
3
4
18 was removed from the list
9 was removed from the list
Process returned -1073741819 (0xC0000005) execution time : 6.699 s
Press any key to continue.
任何有关此问题的输入或帮助将不胜感激,谢谢!
当它到达列表中的最后一个节点时,又名curr->next
等于 null 您正在尝试访问curr->next->data
但下一个是 null。 将您的 if 语句更改为:
while (curr != NULL) {
if(curr->next != NULL && curr->data > curr->next->data){
DeleteNode(curr->data);
curr = head;
}
else curr = curr->next;
if(curr == NULL) break;
}
或等效的东西。 您还可以在 while 循环的条件中检查这一点。
所以基本上你必须在访问之前确保curr->next
不是 NULL
curr->next->data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.