Cracking The Coding Interview/Q 2.3

From Software Engineers Wiki
Jump to: navigation, search

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

EXAMPLE

  • Input: the node c from the linked list a->b->c->d->e
  • Result: nothing is returned, but the new linked list looks like a- >b- >d->e

Answer

To properly delete a note in a linked list, it needs to access the previous node which points to a node to be deleted. Without access to the previous node, it can choose other way; copy the contents from the next node in the list, then remove the next element. But this approach won't work if it the node to be deleted is the last node in the linked list.

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox