Problem solving and discussion on whether a single-linked list has loops (Java implementation)

Source: Internet
Author: User

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
Class
listnode{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 nodes
Private 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.