题目说明
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
一道比较出名的面试题,思路是用一个快指针,一个慢指针。快指针每次向前进两步,慢指针每次向前进一步。如果链表有环的话,快指针因为没法到达链表尽头迟早会和慢指针相遇,因此如果在到达链表尽头前两者相遇就表示链表有环路。
代码
public class LinkedListCycle { public boolean hasCycle(ListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head==null) return false; ListNode slow=head; ListNode fast=head; while(fast!=null) { if(fast.next!=null) fast=fast.next.next; else //如果快指针不能再往前跑了就说明链表没有环 return false; slow=slow.next; if(slow==fast) return true; } return false;//如果到头了说明没有环 } }