Tuesday, August 13, 2013

Coding Exercises Day 11 (Problem #15)

Problem:
Given a circular linked list, implement and algorithm which returns the node at the beginning of the loop.

Definition:
Circular linked list: A corrupt linked list in which a nodes next pointer points to an earlier node, so as to make a loop in the linked list.

Example:
Input: A -> B -> C -> D -> E -> C (same C as earlier)
Ouput: C

Node * findLoopHead(Node *head) {
  if (NULL == head) {
    return NULL;
  }
  int listSize = 1;

  Node *node = head->next;

  while (node != NULL) {
    // Start at head and look at previous nodes
    int i;
    Node *previous = head;
    
    for (i = 0; i < listSize; i++) {
      if (node == previous) {
        return node;
      }
      previous = head->next;
    }
 
    listSize++;
    node = node->next;
  }
  // Not a circular linked list
  return NULL;
}

No comments:

Post a Comment