null
.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
if(head==null) {
return null;
}
ListNode p1 = head;
ListNode p2 = head;
while(true) {
if(p1==null) {
return null;
}
p1 = p1.next;
if(p2==null || p2.next==null) {
return null;
}
p2 = p2.next.next;
if(p1!=null && p2!=null && p1==p2) {
break;
}
}
p2 = head;
while(p1!=p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
没有评论:
发表评论