求有环链表环的起点
可设快慢两个指针,当慢指针走一步时,快指针走两步。假设头节点距离环起点有k步,则当慢指针p1走到环起点时,慢指针p1与快指针p2相距k布,若环长度为l,此时看成p2追赶p1则p2与p1相距l-k步数,从此时开始当p1走l-k步时p1与p2相遇,此时在定义一个指向头节点的指针p,p与p1同时向前走,两者相遇点即为环的起点。
class ListNode{
Object val;
ListNode next;
public ListNode(Object val) {
this.val=val;
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
ListNode p=next;
while(p!=null) {
sb.append(p.val);
p=p.next;
}
return sb.toString();
}
}
public class BeginOfCircle{
public static ListNode beginOfCircle(ListNode head) {
ListNode p1=head;
ListNode p2=head;
while(p1!=null&&p1.next!=null) {
p1=p1.next;
p2=p2.next.next;
if(p1==p2)break;
}
//if(p1!=null||p2!=null)return null;
ListNode p=head;
while(p!=p1) {//相遇点即为环起点
p=p.next;
}
return p;
}
public static void main(String[] args) {
ListNode node=new ListNode(1);
node.next=new ListNode(2);
node.next.next=new ListNode(32);
node.next.next.next=new ListNode(32);
node.next.next.next.next=new ListNode(2);
node.next.next.next.next.next=node.next;
System.out.println(beginOfCircle(node).val);//结果应为2
}
}