码迷,mamicode.com
首页 > 其他好文 > 详细

快慢指针判断链表是否有环

时间:2018-06-26 00:45:56      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:||   两个指针   nbsp   eof   init   tchar   一个   返回   存在   

原来的代码判断是否有环比较的是快慢指针是否有朝一日指向的节点的值相同,

而这是有漏洞的,当输入的节点值有重复时,也可能使代码作出有环的误判,现修改其判断指标为当两个指针的地址相同时,则有环。

然而快慢指针缺点略大,两指针极易错过,当环巨大时,耗费过多的时间,也许存在优化的可能,改天再写吧。。。

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;
}

修改后整题代码如下:

实例:建立一个链表,判断是否存在环
#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;
}

快慢指针判断链表是否有环

标签:||   两个指针   nbsp   eof   init   tchar   一个   返回   存在   

原文地址:https://www.cnblogs.com/jujuno/p/9226718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!