赞
踩
原来的代码判断是否有环比较的是快慢指针是否有朝一日指向的节点的值相同,
而这是有漏洞的,当输入的节点值有重复时,也可能使代码作出有环的误判,现修改其判断指标为当两个指针的地址相同时,则有环。
然而快慢指针缺点略大,两指针极易错过,当环巨大时,耗费过多的时间,也许存在优化的可能,改天再写吧。。。
- int hasloop(linklist l)//快慢指针判断是否有环
- {
- node *p1,*p2;
- if(l == NULL || l->next == NULL) //链表为空,或是单结点链表直接返回头结点
- return 0;
- p1 = p2 = l;
- while(p2->next != NULL && p1->next->next != NULL)
- {
- p1 = p1->next->next;
- p2 = p2->next;
- if(p1->data == p2->data)
- return 1;
- }
- return 0;
- }
-
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
修改后整题代码如下:
实例:建立一个链表,判断是否存在环
- #include "stdafx.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <malloc.h>
- #include <string.h>
-
- typedef struct node
- {
- char data;
- struct node *next;
- }node, *linklist;
-
- void initlist(linklist *l)
- {
- *l = (linklist)malloc(sizeof(node));
- (*l)->next=NULL;
- }
-
- void creatfromhead(linklist l)
- {
- node *s;
- char c;
- int flag = 1;
- while(flag)
- {
- c = getchar();
- if(c != '#')
- {
- s=(node*)malloc(sizeof(node));
- s->data=c;
- s->next = l->next;
- l->next = s;
- }
- else
- flag=0;
- }
-
- }
-
-
- int hasLoop(linklist l)//快慢指针判断是否有环
- {
- node *p1,*p2;
- if(l == NULL || l->next == NULL) //链表为空,或是单结点链表直接返回头结点
- return 0;
- p1 = p2 = l;
- while(p2->next != NULL && p1->next->next != NULL)
- {
- p1 = p1->next->next;
- p2 = p2->next;
- if(p1== p2)
- return 1;
- }
- return 0;
- }
-
-
- int main(int argc, char* argv[])
- {
- linklist l;
- initlist(&l);
- creatfromhead(l);
- if(hasLoop(l))
- printf("有环\n");
- else
- printf("无环\n");
- return 0;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。