Leetcode 141:环形链表
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
ListNode end = null;
while(slow != null && fast != null){
fast = fast.next;
if(fast == null){
return null;
}
slow = slow.next;
fast = fast.next;
if(slow == fast){
end = slow;
break;
}
}
while(end != null && head != null){
if(end == head){
return head;
}
end = end.next;
head =head.next;
}
return null;
}
}
页:
[1]