Finding loop in a singly linked-list

前端 未结 13 1761
梦谈多话
梦谈多话 2020-11-28 18:41

How can I detect that whether a singly linked-list has loop or not?? If it has loop then how to find the point of origination of the loop i.e. the node from which the loop

13条回答
  •  孤城傲影
    2020-11-28 19:17

    You can use hash map also to finding whether a link list have loop or not below function uses hash map to find out whether link list have loop or not

        static bool isListHaveALoopUsingHashMap(Link *headLink) {
    
            map tempMap;
            Link * temp;
            temp = headLink;
            while (temp->next != NULL) {
                if (tempMap.find(temp) == tempMap.end()) {
                    tempMap[temp] = 1;
                } else {
                    return 0;
                }
                temp = temp->next;
            }
            return 1;
        }
    

    Two pointer method is best approach because time complexity is O(n) Hash Map required addition O(n) space complexity.

提交回复
热议问题