Wednesday, 7 August 2013

Is it possible to delete the last node in a linked list?

Is it possible to delete the last node in a linked list?

For example, there is an exercise that says:
Write a function to delete a node from a linked list, given only that pointer
And this is the solution:
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;
}
How can I alter my solution to be able to delete the last element in the
linked list, given only the pointer last node?

No comments:

Post a Comment