python algorithm diary (list series) _leetcode 141. circular linked list

Given a list, the list is determined whether a ring.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.

 

Example 1:

Input: head = [3,2,0, -4] , pos = 1
Output: true
explanation: the list has a ring tail portion connected to a second node.

Example 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

Example 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

Source: stay button (LeetCode)
Link: https: //leetcode-cn.com/problems/linked-list-cycle
method: the speed of the pointer is equal to the time, there is a chain ring

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next or not head.next.next:
            return False
        fast = slow = head
        while(fast.next.next and slow.next):
            fast = fast.next.next
            slow = slow.next
            if not fast.next or not slow.next: #加这个判断避免NoneType
                return False
            if fast == slow:
                return True
        return False

Method 2: Using the characteristics unordered sequence of elements will not be repeated collection (set) of the. The presence of visited nodes set in

Can, not because of the heavy chain with very low efficiency study.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next:
            return False
        visited = set()
        while(head):
            if head in visited:
                return True
            else:
                visited.add(head)
            head = head.next
        return False

 

Published 44 original articles · won praise 0 · Views 1905

Guess you like

Origin blog.csdn.net/weixin_39331401/article/details/104594045