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;//如果到头了说明没有环

         }

}

 

相关文章:

  • 2021-11-13
  • 2021-07-16
  • 2021-11-22
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
猜你喜欢
  • 2022-12-23
  • 2021-07-19
  • 2021-09-27
  • 2021-12-28
  • 2022-01-31
  • 2021-11-14
  • 2021-10-23
相关资源
相似解决方案