141 Linked List Cycle
方法一:使用哈希表存储每次经过的节点。
方法二:使用快慢指针的方法判断。
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def __init__(self):
self.hash = {}
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head and head not in self.hash:
self.hash[head] = 1
head = head.next
if head == None:
return False
else:
return True
Java
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}