this question isLinked List Cycleextension is the location of the start point of the cycle after determining if there is a cycle. FromLinked List Cycleusing the method we can know A=kc-b (don't know the friend can first seeLinked List Cycle). Now suppose there are two nodes, one from the chain head, one from Point B, and after step A, the first node will reach the starting point of cycle, and the second node will pass through the Kc-b, and the original B will also stop at the start of cycle. So we can set up two pointers to know the encounter at the same speed, and the meeting point is the starting point of cycle. The time complexity of the algorithm is O (n+a) =o (2n) =o (n), first walk once to determine the existence of cycle and go to point B, then walk a step to find the starting point of cycle. Space complexity is still O (1). The code is as follows:
Public ListNode detectcycle (ListNode head) { if (head = = NULL | | head.next = = NULL) return null; ListNode Walker = head.next; ListNode runner = Head.next.next; while (Runner!=null && walker!=runner) { walker = Walker.next; if (runner.next!=null) runner = Runner.next.next; else runner = null; } if (runner = = null) return null; Runner = head; while (Walker!=runner) { walker = Walker.next; Runner = Runner.next; } return walker; }
Linked List Cycle Ii--leetcode