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