删除TAIL链表C++中的节点

Remove node at the TAIL Linked List C++

本文关键字:节点 C++ TAIL 链表 删除      更新时间:2023-10-16

All,我正在创建一个函数,该函数将从链表中删除尾部。My函数只适用于一次迭代,但不适用于后续迭代。有人能解释一下吗?

感谢

int List::removeAtTail(){
    if(head == NULL)
    {
        cout << "Node cannot be deleted from an empty linkedList" << endl;
    }
    if(curr->next= NULL)
    {
        curr->next=curr;
    }
    return 0;
}

此外,如果我想返回我删除的元素,我该如何处理?

有很多方法可以做到这一点,以下是一种:

int List::removeAtTail(){
while(curr != NULL) {
   if(curr->next == NULL) { // depending on your implementation you might use Tail
      int temp = *curr;
      delete curr;
      return temp;
   }
   curr = curr->next;
}
return 0;

}

请注意我们是如何遍历列表直到找到最后一项的。在释放内存之前,我们将其存储在一个临时变量中。最后,我们返回存储在临时变量中的值。