给你一个链表的头节点 head
,判断链表中是否有环。
提示:
- 链表中节点的数目范围是
[0, 10^4]
-10^5 <= Node.val <= 10^5
解:快慢指针,如果链表存在环,则快指针和慢指针一定会相遇,如果不存在环,快指针会遇到空节点。
思路:灵茶山艾府
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next;
if (slow == fast)
return true;
}
return false;
}
}
思考:在循环链表中会不会存在快指针跨过慢指针的情况?
答案:不会,快慢指针的相对速度为1。也就是每次移动他们之间的距离差会减少1。