1. 题目分析
在这里我们给两个解题思想
- 基本思想1:哈希表
- 遍历链表
- 用一个哈希表来标记被访问过的点
- 若这个点第二次被访问到,则证明这个链表有回路
- 基本思想2:龟兔赛跑算法
- 定义两个指针,一前一后,前面的那个是兔子,后面那个是乌龟,兔子比乌龟跑得快,兔子一次抛两格,乌龟一次抛一格
- 若这个链表没有回路,则乌龟永远也不可能和兔子相遇,若乌龟与兔子相遇,只能说明这个链表有回路
- 给出图解
我们今天用第二种基本思想来实现这个算法
2. 代码实现
2.1. Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
turtle = head
rabit = head.next
while True:
if(rabit == None or rabit.next == None):
return False
if(turtle == rabit):
return True
else:
turtle = turtle.next
rabit = rabit.next.next
2.2. 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){
return false;
}
ListNode turtle = head;
ListNode rabit = head.next;
while(true){
if(rabit == null || rabit.next == null){
return false;
}
if(turtle != rabit){
turtle = turtle.next;
rabit = rabit.next.next;
}else{
return true;
}
}
}
}