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?

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null) return false;
        ListNode n1 = head, n2 = head;
        while(n2.next != null && n2.next.next != null) {
            n1 = n1.next;
            n2 = n2.next.next;
            if(n1 == n2) return true;
        }
        return false;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容