链表面试题----判断一个单链表是否带环,若带环,求入口点和环的长度

xiaoxiao2021-02-28  68

题目:不用标志位,最多只能用两个指针,如何判断一个单链表是否带环? 分析:定义两个指针slow和fast,slow每次递增一步,fast每次递增两步,如果两者相遇(相等),代表该链表带环,否则没环。 具体实现:

//判断是否有环(快慢指针) bool IsHasCircle(Node* head) { if (head == NULL) return false; Node* slow=head; Node* fast = head->_next; while (fast != NULL &&fast->_next != NULL) { slow = slow->_next; fast = fast->_next->_next; if (slow == fast) return true; } return false; } //求带环链表的入口点 Node* entry(Node* head) { Node* slow = NULL; Node* fast = NULL; assert(head); slow = head; fast = head; while (fast && fast->_next ) { slow = slow->_next; fast = fast->_next->_next; if (fast == slow) break; } if (fast == NULL || fast->_next->_next == NULL) return NULL; slow = head; while (slow != fast) { slow = slow->_next; fast= fast->_next; } return slow; } //求带环链表环的长度 int len(Node* head) { Node* slow = head; Node* fast = head; while (fast&&fast->_next) { slow = slow->_next; fast = fast->_next->_next; if (slow == fast) break; } //因为最后一次slow->_next=fast,不会进入该循环,count少加一次,所以将count置为1 int count = 1; while (slow->_next != fast) { count++; slow = slow->_next; } return count; }
转载请注明原文地址: https://www.6miu.com/read-71964.html

最新回复(0)