数据结构 - 判断单链表是否有环(C++)

版权声明:欢迎转载并请注明出处,谢谢~~ https://blog.csdn.net/chimomo/article/details/7716221
/*
 * Created by Chimomo.
 */

#include "SingleLinkedList.h"

template<class T>
bool SingleLinkedList<T>::hasLoop() {
    Node<T> *pNodeSlow = head, *pNodeFast = head;
    while (pNodeFast && pNodeFast->next) {
        pNodeSlow = pNodeSlow->next;
        pNodeFast = pNodeFast->next->next;
        if (pNodeSlow == pNodeFast) {
            break;
        }
    }
    if (pNodeFast == NULL || pNodeFast->next == NULL) {
        return false;
    } else {
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/chimomo/article/details/7716221