How to determine whether a linked list has a loop

Source: Internet
Author: User
Tags define null

1, the link is to determine whether there is a loop?

(1) Loop definition:

1-2-3-4-5-6-7

| |

----8

As in the case above, it means that there is a loop.

(2) solve the idea:

Description: Use the speed pointer, the slow pointer each time only before further, the quick pointer each step forward two steps, until the slow pointer meets the quick pointer.

2, paste the code

(1) Definition of data structure

#ifndef linklist_h
#define LINKLIST_H
   
#define NULL 0
   
typedef struct MYNODE
{
    int data;
    struct mynode* next;

#endif

(2) Judge the function Isexistlookbackup (Mynode *node), return True if it exists, or false.

1 #ifndef linklist_back_h

#define LINKLIST_BACK_H
#include "LinkedList.h"
bool Isexistlookbackup (mynode* node)
{
    if (node = = NULL | | Node->next = = NULL) return
        false;
    mynode*-node;
    mynode* second = node->next->next;
    while (true)
    {
        if (second = null | | | second->next = NULL) break
            ;
        if (A/= second) return
            true;
        first=first->next;
        Second = second->next->next;
    }
    return false;        
}
   
#endif//! Linklist_h

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.