141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

典型的2 pointer 问题,一个走的快,一个走到慢,如果是cycle就一定会相遇。

public bool HasCycle(ListNode head) {
    if(head == null) return false;
ListNode walker = head;
ListNode runner = head;
while((runner.next != null)&&(runner.next.next != null))
{
walker = walker.next;
runner = runner.next.next;
    if(walker == runner) return true;
}
return false;
}

 

posted @ 2016-09-08 11:15  咖啡中不塌缩的方糖  阅读(99)  评论(0编辑  收藏  举报