Meta Interview Question

Reverse a linked list dynamically. So also, delete the nodes.

Interview Answer

Anonymous

Jan 21, 2015

Not sure if you necessarily *NEED* to delete the nodes. There are multiple ways of doing this. One is to initiate a stack and push values when transversing the LinkedList and then poping the stack back when assigning new values. (This reverses the linked list statically) Option 2, reverse it dynamically by switching all the pointers around so that they now essentially point in the reverse direction as seen below in C++. template LN* reverseList(LN* head) { LN* prev = nullptr; LN* current = nullptr; for (LN* node = head; node != nullptr;) { current = node; node = node -> next; current->next = prev; prev = current; } return current; } Option 3, Read is all the values and store them in a stack. Dynamically delete the Linked List and then dynamically create new nodes by reading the values off the stack. Option 2 is more space efficient.