Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Follow up:
Can you solve it without using extra space?
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */struct listnode {int val; listnode * Next; listnode (int x): Val (x), next (null ){}}; // This is a variant of the linked list cycle. First, use the fast and slow pointers to determine whether it is a cycle list. // then, point slow to the head node, next, continue to traverse. When fast = slow, the value of slow is the entry point of cycle. Class solution {public: listnode * detectcycle (listnode * head) {If (Head = NULL | head-> next = NULL) return head; listnode * fast = head; listnode * slow = head; bool iscycle = false; while (fast! = NULL & slow! = NULL) {slow = slow-> next; If (fast-> next = NULL) return NULL; fast = fast-> next; if (fast = slow) {iscycle = true; break ;}} if (! Iscycle) return NULL; slow = head; while (fast! = Slow) {fast = fast-> next; slow = slow-> next ;}return slow ;}};
Leetcode-linked list cycle II