October 2004
Intermediate to advanced
336 pages
6h 27m
English
This function checks if a singly linked list has a loop in it.
It uses the same ListNode and List classes from the previous examples, but implements a new member method, HasLoop(). A list has a loop if there is some ListNode node in it for which node.next is equal to head.
1. class List { 2. 3. private ListNode head; 4. 5. public List() { 6. head = null; 7. } 8. 9. public List(ListNode ln) { 10. head = ln; 11. } 12. 13. public boolean HasLoop() { 14. 15. // 16. // The algorithm is to start two pointers 17. // at the head of the list; as the first pointer 18. // advances one element in the list, the second ...
Read now
Unlock full access