题目:
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
解答:
两个指针,首先同时指head,一个就用head,步长为1,另一个叫p2,步长为2,如果链表有环,head一定能与p2再次相遇(p2正好比head多走一个环),反之,head与p2永远不会再次相遇。
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode p2 = head;
while (p2 != null && p2.next != null) {
head = head.next;
p2 = p2.next.next;
if (head == p2) {
return true;
}
}
return false;
}
}