I need assistance in figuring out how to erase the first element in the linked l
ID: 3620965 • Letter: I
Question
I need assistance in figuring out how to erase the first element in the linked list without giving a stack dump error, I need to be able to delete the first key without error. Also with the Insert function, I need to have a check that makes sure I am not adding something that is already in the linked List.
I have marked where I need help at. Thanks in advance.
bool LinkedList::erase (const KeyType &key)
{
NodePointer nptr = first;
NodePointer ptr = first;
while (ptr != NULL)
{
***** NEED HELP HERE********* if (ptr->data.key == key && ptr == first)
{
nptr->next = ptr->next;
delete nptr;
return true;
}
if (ptr->data.key == key)
{
cout <<"-------------------------------------------------------------" << endl;
cout <<" The following record has been DELETED:" << endl << endl;
cout <<" Key: " << ptr->data.key << endl;
cout <<" Title: " << ptr->data.title << endl;
cout <<" Author: " << ptr->data.author << endl;
cout <<"-------------------------------------------------------------" << endl;
nptr->next = ptr->next;
delete ptr;
return true;
}
nptr = ptr;
ptr = ptr->next;
}
cout << endl;
cout << "--------------------------------------------------------" << endl;
cout << " - Sorry, record not removed because it was not found. -" << endl;
cout << "--------------------------------------------------------" << endl;
return false;
}
void LinkedList::insert(const ElementType &item)
{
NodePointer cPtr = first;
NodePointer pPtr = first;
NodePointer nPtr = new Node(item);
***********NEED HELP HERE************* if (cPtr == nPtr || pPtr == nPtr)
{
cout << "sorry but there is already a record with that Unique Key. " << endl;
}
if (first == NULL)
{
nPtr->next = first;
first = nPtr;
}
else
{
while(cPtr != NULL && nPtr->data.key >= cPtr->data.key)
{
pPtr = cPtr;
cPtr = cPtr->next;
}
if(cPtr == first)
{
nPtr->next = first;
first = nPtr;
}
else
{
nPtr->next = pPtr->next;
pPtr->next = nPtr;
}
}
}
Explanation / Answer
Where you say : nptr->next = ptr->next; delete nptr; return true; It looks like your assigning the pointers backwards. You're assigning nptr->next to ptr->next and then deleting it on the next line. Try deleting ptr instead or ptr->next = nptr->next; delete nptr; return true; As far as protecting against inserting duplicates in a linked list, just parse through each element with a for loop before looking for a place to insert it.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.