https://leetcode.com/problems/linked-list-cycle/description/
1 public boolean hasCycle(ListNode head) { 2 if (head == null || head.next == null) return false ; 3 ListNode slow = head, fast = head ; 4 while (fast!=null && fast.next!=null && fast.next.next !=null ){ 5 slow = slow.next ; 6 fast = fast.next.next ; 7 if (slow == fast){ 8 return true ; 9 } 10 } 11 return false ; 12 }
time: o(n) space: o(1)
Follow up:
Can you solve it without using extra space?
if you use extra space, then it means using hashMap<val, listNode> time: o(n) space: o(n)