Given a linked list, determine if it has a cycle in it.
Use fast and low pointer. The advantage about fast/slow pointers is that when a circle is located, the fast one will catch the slow one for sure.
Read full article from Leetcode – Linked List Cycle
Use fast and low pointer. The advantage about fast/slow pointers is that when a circle is located, the fast one will catch the slow one for sure.
public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; if(head == null) return false; if(head.next == null) return false; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast) return true; } return false; }
No comments:
Post a Comment