本文共 714 字,大约阅读时间需要 2 分钟。
(原理参考:)
/*判断链表有环,并返回环的入口点*/struct list_head *find_loop_point(struct list_head *head){ struct list_head *slow = head; struct list_head *fast = head; /*如果head为空,或者为单结点,则不存在环*/ if (!head || !head->next) return NULL; /*从链表头开始,slow每次走一步,fast每次走两步,若相遇,则表示链表存在环*/ while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast)/*存在环*/ break; } if (fast != slow)/*不存在环*/ return NULL; /*接下来要判断环的入口点,让slow依旧保存着上面环内相遇节点,让fast重新指向链表头*/ fast = head; /*每次各走一步,当两指针再次相遇时,相遇节点就是环的入口点*/ while (fast != slow) { fast = fast->next; slow = slow->next; } /*返回环的入口点*/ return fast;}
转载地址:http://udqkb.baihongyu.com/