Hello,
I'm writing a code to create a node and delete a node. I've created two functions AddNode and DeleteNode to add and delete nodes, respectfully. I'm currently having an issue when I try to delete a node that head is pointing to. I thought that I had each case accounted for, but after trying for a while, I need another set of eyes. Please identify my error and explain it.
Also, I'm not going to post the other code It's just function calls in main. Assume that you're doing a function call in main for several numbers, you're attempting to delete the node that head points to.
#include "CS163_LLL.h"
#include <cstdlib>
#include <iostream>
usingnamespace std;
list::list()
{ // sets pointers to NULL
head = NULL;
current = NULL;
temp = NULL;
}
void list::AddNode(int addData) //adds at the end
{
node * newnode = new node; // creates a new node pointer and a new node
newnode->next = NULL; // find the node new node points to and set it to null
newnode->data = addData; //adds data to the node
if (head != NULL) // if head points to object then we have a list
{
current = head; // have current point to head
while(current->next != NULL)
{
current = current->next; //traverse
}
current->next = newnode; // if last node found
}
else
{
head = newnode; // assigns head to new node if NULL
}
}
void list:: DeleteNode(int delData)
{
node * delPtr = NULL; // deletes the pointer
current = head; // current points to head's location
while (current != NULL && current->data != delData) // check current isn't NULL
{
temp = current; //trails along behind current
current = current->next; // traverse current to test more conditions
}
if (current == NULL) //data wasn't in the list
{
cout << delData << " was not in the list." << endl;
delete delPtr;
}
else
{
if (delPtr != head)
{
delPtr = current;
current = current->next;
temp->next = current;
}
if (delPtr == head)// if delPtr points to front of list
{
delPtr = current;
current = current->next;
head = head->next;
// temp = NULL;
}
delete delPtr;
cout << "The value " << delData << " was deleted. " << endl;
}
}
void list:: PrintList()
{
current = head; // current points to head
while (current != NULL) // as long as current isn't NULL
{
cout << current->data << endl;
current = current->next;
}
Line 54 is always true. If delData is contained in the very first node (head node), then loop on line 42 will never be executed and temp value will be never set properly. And on line 58 you are trying to use it anyway.