[英]Can someone please explain this code segment?
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;
}
}
抱歉,如果使用错误的格式,那么此网站和C ++通常是新的。 我似乎无法理解此链接列表如何执行删除功能。
在此代码中,它将删除链接列表的节点,该节点的值从调用函数传递为sk2
。
我对它发表了评论,如果不清楚,请询问:)
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
}
}
您似乎想删除以sk2
作为SKU
成员的节点。
第一个if
仅检查head
节点是否为该节点,如果是则将其删除。
如果没有,则else块正在尝试找到它。 然后, nodePtr
是要检查的当前节点,循环条件是:“只要我有一个要检查的节点,那不是正确的节点”。 因此,循环每次都会获取->next
元素。 循环也总是保留前一个节点,因为->next
字段必须相应地设置。
如果循环结束,则会发生以下两种情况之一:
nodePtr
包含正确的节点,它将被删除并以有效方式恢复链接 nodePtr
为NULL
。 然后将发生未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.