Tuesday, July 31, 2012

2.3 removeNode

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

Interesting algorithm. Say you have a->b->c->d and you want to delete B. Since it is a singly linked list, you only have access to b, c d, NOT A. So, instead of doing the normal delete, where you have a->c, and you're done, you overwrite b's data with c's data. Then you "delete" c, have b -> d. Even though you deleted the C node, you deleted B's data and kept C's node. So in fact, you did delete the correct Node.

No comments:

Post a Comment