⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 detectloop.txt

📁 It is an ebook about data structures,mainly linked list
💻 TXT
字号:
How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list. 

Discuss it!          





/*
  Start two pointers at the head of the list
  Loop infinitely
      If the fast pointer reaches a NULL pointer
        Return that the list is NULL terminated
    If the fast pointer moves onto or over the slow pointer 
        Return that there is a cycle
    Advances the slow pointer one node
    Advances the fast pointer two node    
*/

#include <stdio.h>
#include <stdlib.h>

struct linkedList{
    int element;
    struct linkedList* next; 
};

typedef struct linkedList* List;


/* Takes a pointer to the head of a linked list and determines 
   if the list ends in a cycle or is NULL terminated
*/

int DetermineTermination(List *head)
{
    List *fast, *slow;
    fast = slow = head;
    while(1)
    {
        if(!fast || !fast->next)
            return 0;
        else if(fast == slow || fast ->next == slow)
            return 1; // Loop detected
        else{
            slow = slow->next;
            fast = fast->next->next;
        }
    }
}

 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -