141. Linked List Cycle

2020-03-17  本文已影响0人  7ccc099f4608

https://leetcode-cn.com/problems/linked-list-cycle/

image.png

(图片来源https://leetcode-cn.com/problems/linked-list-cycle/

日期 是否一次通过 comment
2020-03-17 0

递归

public boolean hasCycle(ListNode pHead) {
        if(pHead == null || pHead.next == null) {
            return false;
        }
        
        ListNode pSlow = pHead;
        ListNode pFast = pHead;
        
        while(pFast != null && pFast.next != null) {
            pSlow = pSlow.next;
            pFast = pFast.next.next;
            
            if(pSlow == pFast) {
                return true;
            }
        }
        
        return false;  
    }
上一篇 下一篇

猜你喜欢

热点阅读