Shahzad Virani Shahzad Virani - 1 month ago 16
C++ Question

Single Linked List not working (C++)

The following code builds correctly but causes the program to crash when I run it. Can someone please tell me whats wrong with it. I suspect that there is something wrong with the DeleteNode function.

#include <iostream>
#include <cstdlib>

using namespace std;

class list {
private:
typedef struct node {
int data;
node* next;
}* nodePtr; //this means that 'nodePtr' will mean a pointer to the struct node

nodePtr head;
nodePtr current;
nodePtr temp;

public:
list() { //constuctor
head = NULL;
current = NULL;
temp = NULL;
};

void AddNode(int addData) //to add a particular data value
{
nodePtr n= new node;
n->next = NULL;
n->data = addData;

if (head != NULL) { //if a list is already set up
current = head;
while (current->next != NULL) { //to get to the last node in the list
current = current->next;
}
current->next = n;
}
else { // if list is not created
head = n; //new node is front of the list
}
}

void DeleteNode(int delData) //to delete a particular data value
{
nodePtr delPtr = NULL;
temp = head;
current = head;

while (current != NULL && current->data!=delData) { //pass through whole list && find value
temp = current;
current = current->next;
}

if (current = NULL) { //data value not found in list
cout << delData << " was not in the list." << endl;
delete delPtr; //to free up memory space
}
else {
delPtr = current;
current = current->next;
temp->next = current; //to reconnect list

if (delPtr == head) {
head = head->next;
temp = head;
}

delete delPtr;
cout << "The value " << delData << "was deleted." << endl;
}
}

void PrintList() //to print all the data values
{
current = head;

while (current != NULL) { //to go through the data valued of the list
cout << current->data << endl;
current = current->next;
}
}

};



int main()
{
list Shahzad;

Shahzad.AddNode(2);
Shahzad.AddNode(78);
Shahzad.AddNode(28);
Shahzad.AddNode(2398);

Shahzad.DeleteNode(78);
Shahzad.PrintList();
return 0;
}

Answer

Your first problem is with the following line:

if (current = NULL)

You're actually assigning null to current at this point.

This should actually be:

if (current == NULL)