LeetCode(141)——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?


AC:

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fastNode = head;
        ListNode slowNode = head;
        
        while (null != fastNode && null != fastNode.next) {
            slowNode = slowNode.next;
            fastNode = fastNode.next.next;
            
            if (fastNode == slowNode) {
                return true;
            }
        }
        
        return false;
    }
}
快慢指针,如果存在圆,则快指针一定会追上慢指针。如果不存在圆,则快指针一定会走到null指针。

猜你喜欢

转载自blog.csdn.net/weixin_39120845/article/details/79457738
今日推荐