Given a singly linked list and a pointer to a certain node in the list, how would you delete that node in constant time
There are two things that we require to delete a node: the previous node’s address and the next
node. In this case we only know the current nodes address. So to delete it without breaking the list:
Assume that the node comprises of
Data = The data
Next = Pointer to the next node
Also, assume that our linked list looks like this and we only know the current node address.
PREVIOUS NODE -> CURRENT NODE -> NEXT NODE
//Now Copy the contents of the next node to the current node...that’s it
nextnode=currentnode->next
currentnode->data = nextnode->data
currentnode->next = nextnode->next
node. In this case we only know the current nodes address. So to delete it without breaking the list:
Assume that the node comprises of
Data = The data
Next = Pointer to the next node
Also, assume that our linked list looks like this and we only know the current node address.
PREVIOUS NODE -> CURRENT NODE -> NEXT NODE
//Now Copy the contents of the next node to the current node...that’s it
nextnode=currentnode->next
currentnode->data = nextnode->data
currentnode->next = nextnode->next
Comments
Post a Comment
https://gengwg.blogspot.com/