zoukankan      html  css  js  c++  java
  • 【Leetcode】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?

    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;
        }
  • 相关阅读:
    linksys wrt160nv3 刷dd-wrt固件
    win2008 r2 远程桌面问题
    windows server 2008 集成raid卡驱动
    gitlab-ce
    git
    批量发布jar包springboot应用
    gradle
    lvs
    rsyslog
    特殊权限
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8454808.html
Copyright © 2011-2022 走看看