c_cpp 检测链表中的循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 检测链表中的循环相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
#include <bits/stdc++.h>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;

node* insert (node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
    return head;
}

bool DetectLoop (node* head) {
    node *slow = head, *fast = head;
    while (slow && fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
     if (slow == fast)
        return 1;
    }
    return 0;
}

int main () {
    int n;
    node* head=NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head,n);
    }
    if (DetectLoop(head) == 0)
        cout<< "Loop not detected";
    else
        cout<< "Loop detected!";
}
// https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
#include <bits/stdc++.h>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;

node* insert (node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
    return head;
}

bool DetectLoop (node* head) {
    unordered_set <node*> s;
    while (head!=NULL) {
        if (s.find(head) != s.end())
            return 1;
        s.insert(head);
        head = head->next;
    }
    return 0;
}

int main () {
    int n;
    node* head=NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head,n);
    }
    if (DetectLoop(head) == 0)
        cout<< "Loop not detected";
    else
        cout<< "Loop detected!";
}

以上是关于c_cpp 检测链表中的循环的主要内容,如果未能解决你的问题,请参考以下文章

如何检测链表中的循环?

c_cpp 在链表中查找循环的长度

使用 Hare and Tortoise 方法在链表中检测循环

面试:删除链表中的循环 - Java

c_cpp 删除O(1)中链表中的节点

链表循环检测算法