#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define INSERT_NUM 100
#define FAST_POINT_STEP 2
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LinkList, *pNode;
//init the linklist
void initList(pNode *head){
(*head) = (LinkList*)malloc(sizeof(LinkList));
(*head)->next = NULL;
(*head)->data = 9;
}
//insert Element
int insertElem(pNode head, ElemType data){
pNode pInsertNode;
pNode pWork;
pWork = head;
pInsertNode = (LinkList*)malloc(sizeof(LinkList));
//memset(pInsertNode, 0, sizeof(LinkList));
if(pInsertNode == NULL){
return 0;
}
pInsertNode->next = NULL;
pInsertNode->data = data;
while(pWork->next != NULL){
pWork = pWork->next;
}
pWork->next = pInsertNode;
return 1;
}
//print node data one by one
void printList(pNode head){
printf("in the function printList\n");
if(head == NULL){
printf("List is empty----\n");
}
pNode p = head->next;
do{
printf("%d", p->data);
printf("--->");
p = p->next;
}while(p != NULL);
}
//make the LinkList loop
void makeLoop(pNode head){
pNode p = head;
while(p->next != NULL ){
p = p->next;
}
p->next = head->next;
}
//tell if is a loop list?
int isListLoop(pNode head){
int i;
pNode slow = head;
pNode fast = head;
while(fast){
for(i = 0 ; i < FAST_POINT_STEP ; i++){
fast = fast->next;
if(fast == slow)
return 1;
else if(fast == NULL)
return 0;
}
slow = slow->next;
}
return 0;
}
void main(){
int i;
pNode head;
initList(&head);
for(i = 0 ; i < INSERT_NUM ; i++){
insertElem(head, i);
}
makeLoop(head);
//printList(head);
if(isListLoop(head))
printf("is a loop list \n");
else
printf("is not a loop list\n");
}
之前在網上看到有人說,判斷一個鏈表是否有環,還可以使用兩個for循環嵌套的方法,當外層循環步進一個節點時,內層循環就遍歷外層循環節點之後的所有節點,然後比較內外循環的兩個節點。若有節點地址相等,則表明該單鏈表有循環,反之則不存在循環。這種方法無疑效率比較低。而且如果出現下面這種情況的話,會更加麻煩。