How to determine whether there are circles in a singly linked list?

How to determine whether there are circles in a singly linked list?

Answer:let to point p1 ,and p1 , p1 travels the list with one step length ,and p2 with two step length ,

After t step , if p2 come to same pos with p1 , we get there is an circle , otherwise no circle exist in list.

Now let’s prove it .

Both p1 and p2 travel the list ,but with diff step length, where p1 is a one step traveler and P2 is a two step traveler.

Exist and only exist two conditions:

1. Condition one: P2 come to the end. we get there is on circle , it’s trival.

2. Condition two:P2 come to same pos with p1, we got more than one circle exist.

Let there is a circle as the picture below:

clip_image002

Suppose: When p1 come to the first pos (N1) of the circle, P2 is at pos Nk(where K should be one of 1…N).

After t step :

P1 come to N(t1) where t1=t%N

P2 come to N(t2) whereK2=(k+2t)%N

Principal : clip_image004t , t is a natural number , let t+n*m=k+2t , so t1=t2 and P1 come to same pos with P2. where m is natural number

Proof:

Let t=m*n-k we get it, m is a positive natural number.

口.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值