LeetCode (No.141) - endless chain

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.

Here Insert Picture Description
Here Insert Picture Description
Method 1:
Thinking: determining a next node of each node appears earlier in

Method 2:
ideas: Create two nodes, the first node of a slow single-step, two-step a second node fast, if not ring, the faster node will first come to end of the list, exit the loop, returns False. If the ring is present, then the fast second ring node or the third node slow catch ring place until they are equal, True is returned.

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        # 空或者单一个的时候
        if head == None or head.next == None:
            return False

        first = second = head
        while second and second.next:
            first = first.next
            second = second.next.next
            if first == second:
                return True
        return False
Published 114 original articles · won praise 55 · views 80000 +

Guess you like

Origin blog.csdn.net/zuolixiangfisher/article/details/87477928