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

    [Thoughts]

    有一种使用两个指针的方法,一个fast指针,每次移动两步;一个slow指针,每次移动一步。如果两个指针能相遇,则链表具有一个环形。

    public boolean hasCycle(ListNode head) 
    {
        ListNode faster = head;
        ListNode slower = head;
    
        while (faster != null)
        {
            faster = faster.next;
            if (faster == null)
            {
                return false;
            }
            else
            {
                faster = faster.next;
            }
            slower = slower.next;
            if (faster == slower)
            {
                return true;
            }
        }
        return false;
    }

    另一种方法(只是开玩笑)

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null)
                return false;
            int i = 0;
            while(head.next != null){
                i++;
                if (i > 10000){
                    return true;
                }
                head = head.next;
            }
            return false;
        }
    }
  • 相关阅读:
    find
    fdisk
    falcon-eye
    ethtools
    e2fsck
    dpkg
    declare
    df
    debconf-utils
    区块链从零开始做开发(0):hyperledger Fabric2.3安装
  • 原文地址:https://www.cnblogs.com/andrew-chen/p/4226048.html
Copyright © 2011-2022 走看看