Saturday, January 30, 2016

Detecting a Loop in a Singly Linked List

Detecting a Loop in a Singly Linked List


Problem:
Given a singly linked list, find if there exist a loop.
Solution:
1
2
3
4
5
6
7
8
9
10
bool hasLoop(ListNode head) {
  ListNode slow = head, fast = head;
  while (slow != null && fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast)
      return true;
  }
  return false;
}

No comments:

Post a Comment