Linked List Cycle in Python


Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node.

To solve this, we will follow these steps −

  • Take one set as hash set H
  • while head is not null −
    • if head is present in H, then return true
    • add head into H
    • head := next of head
  • return False

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def hasCycle(self, head):
      """
      :type head: ListNode
      :rtype: bool
      """
      hashS = set()
      while head:
         if head in hashS:
            return True
         hashS.add(head)
         head = head.next
      return False

Input

[5,3,2,0,-4,7]
1

Output

true
raja
Published on 16-Jan-2020 09:20:57
Advertisements