2017-04-25 86 views
0
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++一般都是新的。我似乎无法理解这个链表如何执行删除功能。有人可以解释这段代码吗?

+0

这是一个成员功能?它看起来像'head'是一个成员变量,否则我不知道它来自哪里。 – rwols

回答

0

在此代码中,它将删除链接列表的节点,其值为从调用函数传递的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 
    } 
} 
+0

谢谢!正是我正在寻找的! –

0

你似乎要删除其中有sk2作为SKU成员的节点。

第一个if只是检查head节点是否是该节点,如果是,则删除它。

如果没有,那么else块试图找到它。然后nodePtr是当前要检查的节点,并且循环条件是:“只要我有一个节点要检查并且它不是正确的”。 所以循环每次只获取->next元素。此外,该循环始终保持前一个节点,因为必须相应地设置->next字段。

如果循环完成以下两种情况之一会发生:

  1. nodePtr包含正确的节点,它会被delted并以有效的方式
  2. nodePtrNULL恢复了联系。然后会发生未定义的行为。
相关问题