鏈表判斷是否有環與判斷環入口

Detect cycle in a linked list.  A singly-linked data structure is a data structure made up of nodes where each node has a pointer to the next node (or a pointer to null). Suppose that you have a pointer to the first node of a singly-linked list data structure:
  • Determine whether a singly-linked data structure contains a cycle. You may use only two pointers into the list (and no other variables). The running time of your algorithm should be linear in the number of nodes in the data structure.
  • If a singly-linked data structure contains a cycle, determine the first node that participates in the cycle. you may use only a constant number of pointers into the list (and no other variables). The running time of your algorithm should be linear in the number of nodes in the data structure.

You may not modify the structure of the linked list. node

1)判斷有沒有環用在鏈表頭同時放一個「慢」指針(一次走一步),一個「快」指針(一次走兩步),而後判斷可否相遇。 spa

2)相遇位置時,「快」指針比「慢」指針多走了一個環的位置。 指針

    在相遇位置和鏈表頭同時放置兩個「慢」指針,兩個「慢」指針相遇位置就是環入口。 ip

相關文章
相關標籤/搜索