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;//如果到头了说明没有环
    
             }
    
    }
  • 相关阅读:
    团队冲刺2---个人工作总结一(5.25)
    第十二周学习进度
    课堂作业——找水王
    个人冲刺07
    第十五周学习进度情况
    构建之法阅读笔记06
    构建之法阅读笔记05
    第十四周学习进度情况
    个人冲刺06
    个人冲刺05
  • 原文地址:https://www.cnblogs.com/developerY/p/LinkedList_Cycle.html
Copyright © 2011-2022 走看看