Description
https://leetcode.com/problems/linked-list-cycle/
题目大意:判断单链表是否含有环
Solving Ideas
- 使用快慢两个指针判断链表是否含有环,如果两指针相遇即有环
Solution
class Solution {
public boolean hasCycle(ListNode head){
if (head == null) {
return false;
}
ListNode p1 = head, p2 = head.next;
while (p2 != null && p1 != p2) {
p1 = p1.next;
p2 = p2.next;
if (p2 != null) {
p2 = p2.next;
}
}
return p1 == p2;
}
}