class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
//找出有环链表的第一个起始点
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null||head.next.next==null)
return null;
ListNode slow=head.next;
ListNode fast=head.next.next;
while (fast!=slow&&fast!=null&&fast.next!=null) {
fast=fast.next.next;
slow=slow.next;
}
if(fast==null||fast.next==null)
{
return null;
}else{
fast=head;
while(fast!=slow)
{
fast=fast.next;
slow=slow.next;
}
}
return slow;
}
public static void main(String[]args){
//System.out.println("Hello");
ListNode head=new ListNode(1);
head.next=new ListNode(2);
head.next.next=new ListNode(3);
ListNode tmp=new ListNode(4);
head.next.next.next=tmp;
tmp.next=head.next;
Solution s=new Solution();
System.out.println(s.detectCycle(head).val);
}
}
找出有环链表的第一个起始点
最新推荐文章于 2024-08-01 00:32:18 发布