The question of whether a single-linked list has a ring is often encountered during an interview, where an O (1) is required in the general interview, and if there is a ring, the starting position of the ring is obtained.
The following is implemented in Java.
//Single linked list
Classlistnode{intVal; ListNode Next; ListNode (intx) {Val=x; Next=NULL; }} Public classsearchcyclenode{ListNode Equallistnode=NULL;//To record the nodes that are equal when the ring is judged, let's call the "Meet" node.
From the "Meet" node, the first accessible node (starting from the head node of a single linked list) is the starting position of the ring of a single linked list PublicListNode detectcycle (ListNode head) {if(!hascycle (head))return NULL; ListNode P=Head; while(!Isreach (P)) {P=P.next; } returnp; }
Determining the accessibility of nodes from encounters to head nodesPrivate BooleanIsreach (ListNode head) {if(Head==equallistnode)return true; ListNode P=Equallistnode.next; while(p!=Equallistnode) { if(P==head)return true; P=P.next; } return false; }
To determine if there is a ring, through a pointer p step, a pointer Q walk two steps, if can appear p=q case, there is a ring, and record p for "meet" node. Private Booleanhascycle (ListNode head) {if(head==NULL)return false; if(head.next==NULL)return false; ListNode P=Head; ListNode Q=Head.next; while(p!=q) { if(p.next==NULL)return false; P=P.next; if(q.next==NULL)return false; if(q.next.next==NULL)return false; Q=Q.next.next; } Equallistnode=p; return true; }}
Problem solving and discussion on whether a single-linked list has loops (Java implementation)