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