-
单链表的环是什么呢?
有环的定义是,链表的尾节点指向了链接中间的某个节点。比如下图,如果单链表有环,则在遍历时,在通过结点J之后,会重新回到结点D。
-
看了上面的定义之后,如何判断一个单链表是否有环呢?
-
这个可以“快慢指针”来解决。设两个工作指针,一个快一个慢,如果有环的话,它们会必然在某点相遇。
//using step1 and step2 here //if exists a loop, then the pointer which use step2 will catch up with the pointer which uses step1 int HasLoop(LinkList L) { int step1 = 1; int step2 = 2; LinkList p = L; LinkList q = L; //while (p != NULL && q != NULL && q-&g |