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?

    tags提示:two pointers

    采用“快慢双指针”的方法来判断:
    每次slow_pointer前进一格,而fast_pointer前进两格,如若list存在cycle的话,则快指针一定会与慢指针重合。(因为当list存在cycle时,向后遍历是一个无限循环的过程,在此循环中两指针一定会重合)

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head==null || head.next==null) return false;
            
            ListNode slow_pointer = head;
            ListNode fast_pointer = head;
            
            while(fast_pointer!=null && fast_pointer.next!=null){   //向后遍历中出现null,则一定无cycle
                slow_pointer = slow_pointer.next;
                fast_pointer = fast_pointer.next.next;
                
                if(slow_pointer == fast_pointer){    //如果快指针与慢指针重合了,则一定有cycle
                    return true;
                }
            }
            
            return false;
        }
    }



  • 相关阅读:
    算法第四章上机实验报告
    算法第四章作业
    算法第三章上机实验报告
    算法第三章作业
    算法第二章上机实验报告
    算法第二章作业
    第五次c++作业总结
    第三次c++作业总结
    Linux上部署Java项目
    JVM类加载
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444458.html
Copyright © 2011-2022 走看看