-
-
Save startupjing/33c7e74aca2ab63441ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class FindLoopHead { | |
public static void main(String[] args) { | |
MySingleList<Integer> l1 = new MySingleList<Integer>(new Integer[] {1,2,3,4,5,3}); | |
l1.print(); | |
System.out.println("The loop head is: " + findHead(l1)); | |
} | |
/** | |
* find the loop head by using hashset | |
* @param l | |
* @return | |
*/ | |
public static int findHead(MySingleList<Integer> l){ | |
Set<Integer> s = new HashSet<Integer>(); | |
Node<Integer> curr = l.head; | |
while(true){ | |
if(!s.contains(curr.val)){ | |
s.add(curr.val); | |
curr = curr.next; | |
}else{ | |
return curr.val; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you cannot store the value of the node, because different node may have the same value
for example:
1 -> 2-> 4 -> 3 -> 2
is not a circle LinkedList even there exists two node have the same value 2