Java
- 定义一个快指针,一个慢指针,如果有环,慢的迟早会和快的相遇
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
return true;
}
}
return false;
}
- 利用set的不重复
因为Set分支的特点是无序且不可重复,因此通过add方法添加相同的值时,第一次返回为true,后面再加相同元素的话就会返回false,因为元素重复
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet();
while (head != null) {
if (!set.add(head)) {
return true;
}
head = head.next;
}
return false;
}
Python
在Python中定义类经常会用到__init__
函数(方法),首先需要理解的是,两个下划线开头的函数是声明该属性为私有
,不能在类的外部被使用或访问。而__init__
函数(方法)支持带参数类的初始化,也可为声明该类的属性(类中的变量)。__init__
函数(方法)的第一个参数必须为self
,后续参数为自己定义。
__init__()
方法又被称为构造器(constructor)
双指针
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def hasCycle(self , head):
fast = head
slow = head
while fast !=None and fast.next != None:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False