该程序的目标是从列表中删除大于以下元素的所有元素。我设法使该程序执行此任务,但是这样做后立即崩溃,并且此后不打印列表,输出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.
在这个问题上的任何输入或帮助,将不胜感激,谢谢!
When it reaches the last node in the list, aka
curr->next
equals null you are trying to accesscurr->next->data
but next is null. Change your if statement to this:或类似的东西。您还可以在while循环的条件下进行检查。
So basically you have to ensure that
curr->next
is not NULL before you accesscurr->next->data