是否可以删除链表中的最后一个节点?

Ole*_*siy 1 c++ algorithm linked-list data-structures

例如,有一个练习说:

编写一个函数来从链表中删除一个节点,只给出该指针

这是解决方案:

void deleteNode(Node* toDelete) {

    // this function essensially first copies the data from the next pointer
    // and then, deletes the next pointer
    // However, it doesn't work if trying to delete the last element in the list

    Node *temp = toDelete->next;    // create a temp, assign to the one after toDelete
    toDelete->data = temp->data;    // change toDelete's data to the one's after it
    toDelete->next = temp->next;    // change toDelete's next to the one's after it

    delete temp;
    temp = nullptr;
}
Run Code Online (Sandbox Code Playgroud)

如果指针指向最后一个节点,我怎样才能改变我的解决方案以便能够删除链表中的最后一个元素?

Mik*_*our 8

显然你做不到; 前一个节点指向一个有效的节点,没有办法改变它.

您可以做的是将一个标记节点添加到列表的末尾.您永远不会删除该节点,也绝不会使用它来存储数据.然后,您的解决方案将适用于所有数据节点.这不需要对节点结构进行任何更改,但需要更改迭代列表的方式.