【发布时间】:2013-08-07 07:11:16
【问题描述】:
例如,有一个练习说:
写一个函数从链表中删除一个节点,只给出那个指针
这就是解决方案:
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;
}
如果仅指针最后一个节点,我如何更改我的解决方案以删除链接列表中的 last 元素?
【问题讨论】:
-
最后一个节点与其他节点有何不同,您如何对此进行测试?
-
它什么都没有?接下来是一个nullptr
-
所以也许您可以使用该信息为该节点做一些不同的事情。
-
好吧,如果它是一个单链表,而你没有访问到表头的权限,你就做不到。
标签: c++ algorithm data-structures linked-list