Question
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Answer
First, you must note that the empty linked list is not a ring; no extra space is available, that is, the space complexity is O (1). You can use the "Speed Pointer" to check whether the linked list contains a ring, if a fast pointer can catch up with a slow pointer, there is a ring. Otherwise, there is no ring.
/*** Definition for singly-linked list. * class listnode {* int val; * listnode next; * listnode (int x) {* val = x; * Next = NULL; *} */public class solution {public Boolean hascycle (listnode head) {If (Head = NULL) {return false;} listnode fast = head; listnode slow = head; while (fast! = NULL & fast. Next! = NULL) {// you only need to judge whether the fast pointer is null, but note that when fast is the end point, fast. next is null. If fast is determined. next. next, nullpointerexception slow = slow will be reported. next; fast = fast. next. next; If (slow = fast) {return true ;}} return false ;}}
--- EOF ---