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

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

Tips:判断一个链表中是否有环。

思路:设置两个指针,一个快(fast)一个慢(slow),fast指针每次走两步,slow每次走一步。当两个指针相遇,即存在环。若链表中没有环,则fast指针先到达null;

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        boolean hasCy = false;
        ListNode fast = head;
        ListNode slow = head;
        while (fast!=null) {
            if(fast.next!=null){
                fast=fast.next;
                if(fast.next!=null){
                    fast=fast.next;
                    slow=slow.next;
                    if (fast == slow) {
                        hasCy = true;
                        break;
                    }
                }else
                    return false;
            }else
                return false;
        }
        return hasCy;
    }

 

相关文章:

  • 2021-07-08
  • 2021-08-08
  • 2021-09-22
  • 2022-01-06
  • 2022-02-11
  • 2021-12-16
猜你喜欢
  • 2022-01-09
  • 2021-04-23
  • 2021-09-02
  • 2021-09-14
  • 2021-12-05
  • 2022-02-02
  • 2022-01-05
  • 2021-10-04
相关资源
相似解决方案