/** Algorithm Function: create a single-chain table to determine whether a single-chain table has a ring. * Function Description: * 1. initlinklist (): creates a single-chain table with no loops and no headers. * 2. initlooplist (): Creates a linked list with loops. * 3. islooplink (): determines whether the linked list has a ring. * @ Author: xiaoq-ohmygirl * @ time: 2012-06-25 **/# include <stdio. h> # include <malloc. h> # include <stdlib. h> # define maxnode 5 // Type Def struct linknode {int data; linknode * Next;} linknode, * linklist; // The header node insertion method sets up the initlinklist (linklist & L, int N) {L = (linklist) malloc (sizeof (linknode); If (! L) {return 0;} scanf ("% d", & L-> data); L-> next = NULL; linklist P; For (INT I = n-1; i> 0; I --) {P = (linklist) malloc (sizeof (linknode); scanf ("% d", & P-> data ); p-> next = L-> next; L-> next = P;} return 1;} // create a loop where the K element of a single-chain table is located, the pointer from the End Node points to this. Assert (n> = k) int initlooplink (linklist & L, int N, int K) {L = (linklist) malloc (sizeof (linknode); If (! L) {return 0;} scanf ("% d", & L-> data); L-> next = NULL; linklist P, node; For (INT I = n-1; i> 0; I --) {P = (linklist) malloc (sizeof (linknode); scanf ("% d", & P-> data ); p-> next = L-> next; L-> next = P;} node = L; For (INT I = 0; I <K; I ++) {node = node-> next;} p = node; while (node-> next! = NULL) {node = node-> next;} node-> next = P; return 1;} // test whether a single-linked table has a ring. Algorithm idea: if a single-chain table has a ring, the two pointers that initially point to the head of the linked list take two steps and one step, and the pointer will eventually be intersecting. Otherwise, there must be no ring. Linklist islooplink (linklist L) {linklist first = L, second = L; while (first! = NULL & First-> next! = NULL) {First = first-> next; second = Second-> next; If (first = Second) {return first ;}} return NULL ;} main () {linklist L = NULL, P = NULL; initlinklist (L, maxnode); P = islooplink (l); printf ("% s", P = NULL? "Not loop": "loop"); initlooplink (L, maxnode, 2); P = islooplink (l); printf ("% s", P = NULL? "Not loop": "loop"); System ("pause"); Return 0 ;}