How do we find if a linked list has a loop..
Anonymous
You could make a hashmap of all the nodes and youll know when you have run across a node for a second time...its O(n) space and time though... if you want O(n) time and O(1) space: 1. record the first node somewhere (Node first = current) 2. for every node you visit (from the beginning) ...a. take a note of what the next node is (Node nextNode = current.next) ...b. for the node you are currently on, have it point to the previous node (this will be null in the beginning) (current.next = previous) ...c. keep note of the current node before you move onto the next node (previous = current) ...d. move onto the next node (current = next) ...e. if you are pointing to null, then check to see if previous==first...if it does, then you have a loop..otherwise, there is no loop
Check out your Company Bowl for anonymous work chats.