Finding loop in a singly linked-list

前端 未结 13 1756
梦谈多话
梦谈多话 2020-11-28 18:41

How can I detect that whether a singly linked-list has loop or not?? If it has loop then how to find the point of origination of the loop i.e. the node from which the loop

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 19:04

    Another solution

    Detecting a Loop:

    1. create a list
    2. loop through the linkedlist and keep on adding the node to the list.
    3. If the Node is already present in the List, we have a loop.

    Removal of loop:

    1. In the Step#2 above, while loop through the linked list we are also keep track of the previous node.
    2. Once we detect the loop in Step#3, set previous node's next value to NULL

      #code

      def detect_remove_loop(head)

          cur_node = head
          node_list = []
      
          while cur_node.next is not None:
              prev_node = cur_node
              cur_node = cur_node.next
              if cur_node not in node_list:
                  node_list.append(cur_node)
              else:
                  print('Loop Detected')
                  prev_node.next = None
                  return
      
          print('No Loop detected')
      

提交回复
热议问题