Amazon Interview Question

Finding out if a linkedlist has a loop or not. Mergin two sorted linkedlists.

Interview Answers

Anonymous

Oct 4, 2013

The last node can point to a node somewhere in the middle of the list and make a loop and not necessarily to the initial node.

Anonymous

Oct 4, 2013

Question 1: class Node { public: Node() {next = NULL;} ~Node() {} Node* next; }; bool hasLoop(Node* node) { if(!node) { return false; // or throw } for(Node* n = node; n->next != NULL; n = n->next) { // if we hit the initial node _again_, there's a loop // NOTE: this uses node addresses for comparison if(n->next && n->next == node) { return true; } } return false; }