void removeNode(string sk2) {
nodelist *nodePtr, *previousNode; // keeps the list in memory
if (head->SKU == sk2) {
nodePtr = head->next;
delete head;
head = nodePtr;
} else {
nodePtr = head;
previousNode = NULL;
while (nodePtr != NULL && nodePtr->SKU != sk2) {
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
Sorry if its in the wrong format, im new to this site and c++ in general. I cant seem to understand how this linked list preforms the delete function.
In this code it is deleting the node of the linked list which is having its value as sk2
passed from calling function.
I have put comments on it please refer if something is not clear you can ask me :)
void removeNode(string sk2){ // function having string as a argument
nodelist *nodePtr, *previousNode; //keeps the list in memory Variable of type nodelist
// here it is checking with the head of the link list whether that matches with the argument, as all linked list start with the Head
if (head->SKU == sk2){
nodePtr = head->next;
delete head; // if so then delete that node
head = nodePtr; // and reassign the head to new node
}
// if head parameter is not matching
else
{
nodePtr = head;
previousNode = NULL;
// travel up-to the node which has a data as a string passed as argument
while (nodePtr != NULL && nodePtr->SKU != sk2)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
previousNode->next = nodePtr->next;
delete nodePtr; // if found then delete that node
}
}
You appear to want to remove a node which has sk2
as SKU
member.
The first if
just checks if the head
node is the one and deletes it if it is.
If not then the else block is trying to find it. nodePtr
is then the current node to check and the loop condition is: "as long as i have a node to check and it's not the right one". So the loop just gets the ->next
element every time. Also the loop always keeps the previous node because the ->next
field will have to be set accordingly.
If the loop finishes either one of two things will happen:
nodePtr
contains the right node and it will be delted and the links restored in a valid fashion nodePtr
is NULL
. Then undefined behaviour will occur.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.