Wednesday, November 26, 2014

detect Linked List Cycle



基本思想就是使用两个指针~~~~一个在前步进为2,一个在后步前为1,如果前面的指针可以追到后面的指针表明有环

bool hasLoop(Node *head) {
  Node *slow = head, *fast = head;
  while (fast && fast->next) {
    slow = slow->next;
    fast = fast->next->next;
    if (slow == fast)
      return true;
  }
  return false;
}

No comments:

Post a Comment