检查链表中是否有环

Method One

int is_cycle_list(Node* head) {
    Node *temp, *current, *next;
    if(!head)
         return FALSE;
         
    temp = NULL;
    current = head;
    next = head->next;
    current->next = temp;
    
    while(next) {
         if(next == head) {
              return TRUE;
         }
         temp = current;
         current = next;
         next = next->next;
         current->next = temp;
    }
    
    return FALSE;
}

Method Two

int is_cycle_list(Node *list) {
    Node *one_step, *two_step;
    one_step = two_step = list;
    if(!list) {
         return FALSE;
    }
    
    while(two_step) {
         one_step = one_step->next;
         two_step = two_step->next;
         if(!two_step) {
              return FALSE;
         }
         two_step = two_step->next;
         if(one_step == two_step) {
              return TRUE;
         }
    }
    return FALSE;
}

 

posted @ 2013-11-25 15:37  alexeyqian  阅读(174)  评论(0编辑  收藏  举报