zoukankan      html  css  js  c++  java
  • [LeetCode]LinkedList Cycle

    题目说明

    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;//如果到头了说明没有环
    
             }
    
    }
  • 相关阅读:
    Bootsrap 的 Carousel
    Bootstrap 的 Tooltip 和 Popover
    JavaScript 继承
    Bootstrap 的 Collapse
    Bootstrap 组件之 Panel
    Bootstrap 组件之 List group
    Bootstrap 组件之 Nav
    使用 classList API
    Bootstrap 的 Dropdown
    Bootstrap 的 Modal
  • 原文地址:https://www.cnblogs.com/developerY/p/LinkedList_Cycle.html
Copyright © 2011-2022 走看看