单链表循环检测

2016-02-23  本文已影响103人  wundead
#include <stdio.h>

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

int check_cycle(node_t *list)
{
    node_t *a = list, *b = list;

    while (b) {
        a = a->next;
        b = b->next;        

        if (!b) {
            break;
        }

        b = b->next;

        if (b == a) {
            return 1;
        }
    }

    return 0;
}

int main()
{
    int i;
    node_t list[100];

    for (i = 0; i < 100; i++) {
        list[i].next = &list[i+1];
    }

    list[99].next = &list[50];
    if (check_cycle(list)) {
        printf("list cycle detected!\n");
    } else {
        printf("list ok!\n");
    }

    list[99].next = NULL;
    if (check_cycle(list)) {
        printf("list cycle detected!\n");
    } else {
        printf("list ok!\n");
    }

    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读