链表中是否有环以及环的位置
package swordoffer;
public class Loop <AnyType>{
private static class Node <AnyType>{
public Node<AnyType> next ;
public AnyType data ;
public Node(Node<AnyType> next , AnyType data){
this.next = next ;
this.data = data ;
}
}
boolean hasCircle (Node<AnyType> head ){
Node fast = head ,slow = head ;
Node<AnyType> encounter ;
while (fast!=null && fast.next!= null){
fast = fast.next.next ;
slow = slow.next ;
if (fast== slow){
encounter = fast ;//用在后面
return true ;
}
}
encounter = null ;
return false ;
}
/**
* s +nr =2s
* s = x+y
* 得到
* nr = x+y
* x =nr-y
* 也就是说,p1 从链表 开始处遍历,p2从encounter处遍历,一次都 移动 一步,则当p1到达入口点时,p2移动nr-y步
* 两者恰好在环的入口 点处相遇了。
* @param head
* @param encounter
* @return
*/
Node<AnyType> findEntry (Node<AnyType> head , Node<AnyType> encounter) {
Node<AnyType> p1 = head , p2 = encounter ;
while(p1!= p2 ){
p1= p1.next ;
p2 = p1.next ;
}
return p1 ;
}
}
参考 了
http://blog.csdn.net/wuzhekai1985/article/details/6725263

浙公网安备 33010602011771号