Skip to content

Instantly share code, notes, and snippets.

@startupjing
Created June 29, 2014 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/33c7e74aca2ab63441ae to your computer and use it in GitHub Desktop.
Save startupjing/33c7e74aca2ab63441ae to your computer and use it in GitHub Desktop.
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;
}
}
}
}
@jyuan
Copy link

jyuan commented Dec 30, 2014

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment