题目详情
给你一个链表的头节点 head ,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。
如果链表中存在环 ,则返回 true 。 否则,返回 false 。
分析
通过设置快慢指针,快指针每次前进两步,慢指针每次前进一步,如果链表存在环,快慢指针一定会相遇,可以自己画一个带环的链表模拟快慢指针的前进过程。
分析一下边界条件,由于快指针是每次前进两个,所以我们最开始需要保证如下的情况
// 特殊的三种情况
if (head == null || head.next == null || head.next.next == null) {
return false;
}
初始情况排除后,考虑每次前进过程中:
// 这里的f是快指针
if (f.next == null || f.next.next == null) {
// 无环
return false;
}
快指针保证后,慢指针的情况就不用考虑了,因为慢指针是沿着快指针走过的路在走。
Java完整代码
代码中有详细的注释,非常的清楚。
/**
* 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) {
// 特殊的三种情况
if (head == null || head.next == null || head.next.next == null) {
return false;
}
ListNode s = head.next; // 慢指针每次前进一格
ListNode f = head.next.next; // 快指针每次前进两格
while (s != f) {
// 遍历这个链表,发现f后面是空,意味着没有循环
if (f.next == null || f.next.next == null) {
// 无环
return false;
}
f = f.next.next;
s = s.next;
}
// 出上面这个while循环,表示链表存在环
return true;
}
}
Python完整代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# Floyd快慢双指针法
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head is None:
return False # 防止为空,直接返回
fastPtr = head # 快指针
slowPtr = head # 慢指针
while fastPtr.next is not None and fastPtr.next.next is not None:
slowPtr = slowPtr.next
fastPtr = fastPtr.next.next
if slowPtr == fastPtr:
return True
return False
总结
不管是Java实现还是python实现,思想都是一样的,使用快慢指针解决问题。