I am looking to find a way to detect cycle in linked list using Array in PHP. Please note I am aware of two pointer approach but I am keen on understanding approach if it is feasible to achieve this with php array.
in Java code sample on leetcode is as below:
public boolean hasCycle(ListNode head) { Set<ListNode> nodesSeen = new HashSet<>(); while (head != null) { if (nodesSeen.contains(head)) { return true; } else { nodesSeen.add(head); } head = head.next; } return false; }
Advertisement
Answer
Based on the given info I would rewrite it like this utilizing also an array as hashmap for visited nodes.
function hasCycle(SplDoublyLinkedList $list): bool { $nodesSeen = []; $list->rewind(); while ($current = $list->current()) { if (isset($nodesSeen[$current])) return true; $nodesSeen[$current] = true; $list->next(); } return false; }
Testing with having a cycle on a
.
$list = new SplDoublyLinkedList(); $list->push('a'); $list->push('b'); $list->push('c'); $list->push('a'); var_dump(hasCycle($list));
true
Testing with having no cycle.
$list = new SplDoublyLinkedList(); $list->push('a'); $list->push('b'); $list->push('c'); $list->push('d'); var_dump(hasCycle($list));
false