copyright:Craking coding interview
109 Cracking the Coding Interview | Data Structures
2.5 Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C
第一种方法:使用Hashtable<Integer, String>或Hashtable<Node, String> 均可,假定Node.data可以唯一标识一个节点,否则的话,应该用第2种Hashtable泛型用法。
第二种方法查看链接:http://article.yeeyan.org/view/9225/173996
import java.util.Hashtable;
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
next = null;
}
}
public class Solution{
public static Node getLoopNode1(Node head){
Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
Node p = null;
for(p=head;p != null;p = p.next){
if(hash.containsKey(p.data)){
return p;
}else{
hash.put(p.data, "");
}
}
//the list isn't loop list
//if(p == null)
return null;
}
public static Node getLoopNode2(Node head){
Node p1 = head, p2 = head;
//ewhen the start :p1.data == p2.data == head.data,
//so Usage:do{} while();
do{
p1 = p1.next;
p2 = p2.next.next;
}while(p1.data != p2.data && p2 != null && p2.next != null);
//the list isn't loop list
if(p2 == null || p2.next == null)
return null;
p1 = head; int i=0;//
while(p1.data != p2.data){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
private static void printLoopNode(Node head){
Node p = null;
Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
for(p = head;p != null;p = p.next){
if(hash.containsKey(p.data)){
System.out.print(p.data+" ");
break;
}else{
hash.put(p.data, "");
System.out.print(p.data+" ");
}
}
System.out.println();
}
public static void main(String[] args){
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
//head.next.next.next.next.next = head.next.next;
Solution.printLoopNode(head);
Node n = Solution.getLoopNode1(head);
System.out.println("loop node = " + (n != null ? n.data : null));
}
}