Given a pointer to a node in a singly linked list, how do you delete the node ?
A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
struct node *temp = node_ptr->next; node_ptr->data = temp->data; node_ptr->next = temp->next; free(temp);In java, the code would look something like this :
1 | public void deleteNode(Node node){ |
2 | Node temp = node.next; |
3 | node.data = temp.data; |
4 | node.next = temp.next; |
5 | //do nothing with temp and let the garbage collector remove it |
6 | } |
0 comments:
Post a Comment