对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展:
你能给出不利用额外空间的解法么?
#方法一,利用集合
class Solution:
def detectCycle(self , head ):
my_set = {''}
while head != None:
if head in my_set:
return head
else:
my_set.add(head)
head = head.next
return None
'''
#方法二,逐个删除
class Solution:
def detectCycle(self , head ):
while head != None:
if head == head.next:
return head
tmp_node = head.next
head.next = head
head = tmp_node
return None
'''
# write code here 不知道什么毛病,第二种逐个删除就是报错
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return ListNode类 # class Solution: def detectCycle(self , head ): # write code here if not head: return None slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: node1 = head node2 = slow while node1 != node2: node1 = node1.next node2 = node2.next return node1 return None
python版:
class Solution:
def detectCycle(self , head ):
if not head:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow = slow.next
fast = fast.next
return fast
return None
class Solution { public: ListNode *detectCycle(ListNode *head) { if(head == NULL){ return 0; } ListNode* slow = head; ListNode* fast = head; while(fast != NULL && fast->next != NULL){ slow = slow->next; fast = fast->next->next; if(slow == fast){ break; } } if(fast == NULL || fast->next == NULL){ return NULL; } slow = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return slow; } };