leetcode - 141-- circular linked list,

Subject description:

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:

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

Here Insert Picture Description
Example 2:

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

Here Insert Picture Description
Example 3:

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

Here Insert Picture Description


Problem-solving ideas:

Use double-pointer speed, fast hands each take two steps, each step by slow pointer. Traversing the above flow, if the pointer quickly come None, then there is no ring (inner annular absence of chain termination). If the fast and slow pointer as the pointer, then there is a ring


Code:

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def hasCycle(self, head):

        if head == None: return False
        slow = head
        fast = head.next
        while fast!= slow:
            if fast == None or fast.next == None or fast.next.next == None:
                return False

            slow = slow.next
            fast = fast.next.next
        return True

Reference links:
leetcode endless chain-141-


Topic Source:
https://leetcode-cn.com/problems/linked-list-cycle

Published 378 original articles · won praise 43 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/105133256