【问题标题】:Can someone please explain this code segment?有人可以解释一下这个代码段吗?
【发布时间】:2017-04-25 10:11:07
【问题描述】:
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++。我似乎无法理解这个链表是如何执行删除功能的。

【问题讨论】:

  • 这是一个成员函数吗?看起来head 是一个成员变量,否则我不知道它来自哪里。

标签: c++ linked-list


【解决方案1】:

在这段代码中,它删除了链表的节点,该节点的值是从调用函数传递的sk2。

我已经把cmets放在上面了,如果有不清楚的地方可以问我:)

  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 
     }
}  

【讨论】:

    【解决方案2】:

    您似乎想要删除一个具有sk2 作为SKU 成员的节点。

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

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

    如果循环结束,会发生以下两种情况之一:

    1. nodePtr 包含正确的节点,它将被删除并以有效的方式恢复链接
    2. nodePtr 是NULL。然后会发生未定义的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多