我正在尝试创建一个简单的链接列表并添加基本功能(添加,删除,打印)但是我遇到了del函数的问题,每当我尝试del del a node我得到这条消息。 “类içinestruct.exe中0x00119EC1处的未处理异常:0xC0000005:访问冲突读取位置0x00000004。”
LİST.H
#ifndef LIST_H
#define LIST_H
class list{
public:
struct node {
char data;
node *next;
};
typedef struct node NodePtr;
NodePtr *head, *current, *temp;
list();
void add(char addData);
void del(char deleteData);
void printList();
void menu();
};
#endif
SOURCE.CPP
#include <cstdlib>
#include <iostream>
#include "List.h"
using namespace std;
list::list(){
head = NULL;
current = NULL;
temp = NULL;
}
void list::add(char addData){
NodePtr *newNode = new NodePtr;
newNode->data = addData;
newNode->next = NULL;
if (head != NULL){
current = head;
while (current->next != NULL){
current = current->next;
}
current->next = newNode;
newNode->next = NULL;
}
else
{
head = newNode;
}
}
void list::printList(){
current = head;
while (current != NULL){
cout << current->data << endl;
current = current->next;
}
}
void list::del(char deleteData){
NodePtr *delPtr;
delPtr = NULL;
temp = head;
current = head;
while (current != NULL&¤t->data != deleteData){
temp = current;
current = current->next;
}
if (current = NULL){
cout << deleteData << "was not in the list" << endl;
delete delPtr;
}
else
{
delPtr = current;
current = current->next;
temp->next = current;
if (delPtr == head){
head = head->next;
temp = NULL;
}
delete delPtr;
cout << "value" << deleteData << "was deleted" << endl;
}
}
void list::menu(){
cout << "Choose an operation\n"
<< "A: Add Task\n"
<< "S: Search for Task\n"
<< "L: List All Tasks\n"
<< "R: Remove Task\n"
<< "E: Exit\n";
}
的main.cpp
#include <cstdlib>
#include <iostream>
#include "List.h"
using namespace std;
int main(){
char addData, deleteData, operation;
list tasks;
tasks.menu();
cout << "Choose an Operation\n";
cin >> operation;
while (operation!='E' && operation!='e'){
switch (operation)
{
case 'A':case'a':
cout << "data girin";
cin >> addData;
tasks.add(addData);
break;
case 'S': case's':
break;
case 'L': case 'l':
tasks.printList();
break;
case 'R': case 'r':
cin >> deleteData;
tasks.del(deleteData);
break;
default:
break;
}
tasks.menu();
cin >> operation;
}
}
答案 0 :(得分:0)
if(current = NULL){
最有可能是if (current == NULL){
(注意两个等号)。或者只是if (!current)
答案 1 :(得分:0)
if (current = NULL){ // it's supposed to be == here
cout << deleteData << "was not in the list" << endl;
delete delPtr;
}