141-linked-list-cycle
Question
https://leetcode.com/problems/linked-list-cycle/description/
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Example:
Thought Process
- Hash Table
- Use hash table to record the node visited
- Time complexity O(n)
- Space complexity O(n)
- Two Pointer
- Classic Tortoise and Hare Algorithm or Floyd's Cycle detection algorithm
- Slow pointer move at the pace of 1 and fast pointer moves at the pace of 2
- Fast pointer is the one who catch up with slow
- If slow and fast meet, we know there is cycle
- Time complexity O(n)
- Space complexity O(1)
Solution
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast!= null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}