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

Loop List

时间:2014-11-22 01:58:08      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   os   sp   for   strong   on   

Loop List is very common in interview. This article we give a more strict short statement about its solving.

 

One method to check if there‘s a loop in a list is to use two speed pointers. But most of articles did not give a proof.

 

Assume we have a list:

ListNode* head;

Then, we set two pointers start from the head, and one pointer added by 1 step, the other added by 2 steps:

ListNode* p1 = head, *p2 = head;
...
p1 = (p1 -> next) -> next;
p2 = p2 -> next;

Now, we need to proof that, if there‘s a loop in the list, p1 will meet p2.

  1. p1 obviously will exceed p2.
  2. As p1 can only added two steps every time, there‘re only two relative positions between p1 and p2.
    • p1 just before p2. Then as p1 updates first, p2 updates second, they‘ll meet.
    • There‘s a node between p1 and p2. As p1 updates first, they‘ll meet.

 

Loop List

标签:style   blog   io   ar   os   sp   for   strong   on   

原文地址:http://www.cnblogs.com/kid551/p/4114546.html

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