Determine if a linked list has a ring, and the entry of the ring

Source: Internet
Author: User

Give a list, first determine whether the linked list with a ring, if the band ring, to find the entrance of the ring.

Determine if you have a ring: use a fast or slow pointer. Fast pointer every two steps, slow hands step, if the two at a point in the phase

The chain strap ring.

The implementation code for the function is given below:

typedef struct LINKNODE{DATATYPE data;struct Linknode *next;} linknode,*plinknode;typedef struct Linklist{linknode *phead;} Linklist,*plinklist;plinknode iscircle (plinklist plist) {assert (plist); if (null = = Plist->phead) {printf ("the list is empty \ n") ; return NULL;} Plinknode fast = Plist->phead;plinknode slow = plist->phead;while (Fast && fast->next) {fast = Fast->n Ext->next;slow = slow->next;if (fast = = slow) return fast;} return NULL;}

If

If the chain strap rings, look at the following diagram:


Code:

Plinknode Firstcrossnode (plinklist plist) {assert (plist), if (NULL = = Plist->phead) {printf ("list is empty \ n"); return NULL;} Plinknode ret = iscircle (plist), if (ret = = NULL) {printf ("list without ring \ n"); return NULL;} Plinknode fast = Plist->phead;plinknode slow = ret;while (fast) {fast = Fast->next;slow = slow->next;if (Fast = = s) Low) return fast;}}


Determine if a linked list has a ring, and the entry of the ring

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.