141.环形链表
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode low = head,fast = head;
while(fast != null && fast.next != null) {
low = low.next;
fast = fast.next.next;
if(low == fast) {
return true;
}
}
return false;
}
}
运行截图:
142.环形链表II
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode low = head,fast = head;
while(fast != null && fast.next != null) {
low = low.next;
fast = fast.next.next;
if(low == fast) {
ListNode third = head;
while(third != low) {
low = low.next;
third = third.next;
}
return low;
}
}
return null;
}
}
截图如下: