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;
        }
    }



  • 相关阅读:
    个人工作量
    个人作业
    本周psp
    典型用户和场景总结
    排球比赛计分规则功能说明书
    我与计算机
    个人作业
    《怎样成为一个高手》读后感
    第十八周个人作业
    第十六周 项目耗时记录
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444458.html
Copyright © 2011-2022 走看看