利用字节对齐判断链表是否有环,主要的思路就是根据字节对齐规则将字节空隙利用起来。利用字节空隙来标记遍历过的节点。
#include <stdio.h>
//链表节点
struct Node{
int value;
struct Node *next;
};
//创建链表
struct Node* createNode(int n){
//头节点
struct Node *head = new struct Node;
head->value = 1;
head->next = NULL;
struct Node *p = head;
for(int i=2;i<=n;i++){
p->next = new struct Node;
p->next->value = i;
p->next->next = NULL;
p = p->next;
}
//将尾部连接到第二个节点形成有环的链表
p->next = head->next;
//返回头节点
return head;
}
//判断链表是否有环,有则返回成环的第一个节点,无则返回NULL
struct Node* gethuan(struct Node *head){
struct Node *p = head;
char *pt = NULL;
while(p!=NULL){
pt = (char*)p+4;//找到字节空隙
//将遍历过的节点在字节空隙置1做为标记,如果找到标记则有环,且该节点就是环的头节点
if(*pt==1){
return p;
}
*pt = 1;
p = p->next;
}
return NULL;
}
int main()
{
struct Node *head = createNode(5);
struct Node *p = gethuan(head);
if(p==NULL){
printf("NO\n");
return 0;
}
printf("%d\n",p->value);
return 0;
}