InterviewSolution
Saved Bookmarks
| 1. |
How can you delete a value from a linked list if you have a pointer to it? It's important to note that no other node, not even the head, is provided with a pointer. |
|
Answer» The approach is to copy the DATA from the next NODE to the node that will be erased, then delete the node that will be deleted. void delNode(ListNode* ptr){ // If the node to be deleted is the // last node of linked list if (!ptr->next) { free(ptr); // this will simply make the node_ptr NULL. return; } // if node to be deleted is the first or // any node in between the linked list. ListNode* temp = ptr->next; ptr->val = temp->val; ptr->next = temp->next; free(temp);}It's vital to keep in mind that this method will only operate if the given reference does not point to the last node. Because you don't have the following node to copy the INFO from if it's the last node. We can make the final node a DUMMY node to make this solution work. However, the programs/functions that use this function should be CHANGED as well. |
|