且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定链表是否包含循环?

更新时间:2022-12-13 21:07:11

简单.保持两个指针到列表中.在每个步骤中,将一个指针前移单个链接,将另一个指针前移两个链接.测试以查看它们是否指向相同的元素.如果是这样,您就有一个循环.如果没有,请重复直到找到一个循环或到达列表的末尾.

Easy. Maintain two pointers into the list. At each step, advance one pointer by a single link, and advance the other by two links. Test to see if they point to the same element. If so, you have a loop. If not, repeat until you find a loop or you reach the end of the list.