例如,有一个练习说:
编写一个函数从链表中删除一个节点,只给定那个指针
这是解决方案:
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;
}
仅给定指针最后一个节点,如何更改我的解决方案以删除链表中的最后一个元素?