I am working on a linked list to try and understand them a bit better. I currently have a function to insert a node into the list, display the list and delete the most recent node in the list. I am having trouble with a function which takes an int pos as an argument and deletes the int found in the pos position of the list
I would appreciate it if someone could fill me in on how to go about implementing this function in the ListOfInts classes (psuedo code or functional code)
While I'm here, at some point you're going to have to write the destructor so that you don't leak memory. By the time the list has been destroyed, everything that was allocated using new must have been deallocated using delete.
i was going to try the following code, but since i have gone past the node before, how do i link it with the node after.. before deleting the node in pos
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int ListOfInts::deleteInt(int pos)
{
ListNodePtr tempPtr = head;
int count = 0;
while (tempPtr != NULL)
{
if (count == pos)
{
return tempPtr->data;
//delete node code
}
count++;
tempPtr = tempPtr->next;
}
}
int ListOfInts::deleteInt(int pos)
{
ListNodePtr tempPtr = head;
int count = 0;
ListNodePtr nodeBefore = nullptr;
while (tempPtr != NULL)
{
if (count == pos)
{
// in here, make the nodeBefore point at the node after
// then delete this node that you have found is the right node to delete
return someValue;
}
count++;
nodeBefore = tempPtr;
tempPtr = tempPtr->next;
}
}
Thanks a lot Repeater! You've been very helpful again.. code below works perfect and now i understand a lot more about linked lists as a whole.
Regarding typedef, our lecturer told us to use it as it saves us from typing in the pointer * every time, although this is not a lot to type so i can't see the benefit either. maybe he was just trying to introduce us to what we can do with typedef