1.判断链表是否带环
用快慢指针求,快指针一次两步,慢指针一次走一步,如果带环的话那么快指针最终会与慢指针相遇,如果快指针fast或者fast->next走到NULL的话,则说明链表不带环。
pair<Node<int>*, bool> IsExitsLoop(Node<int>* head)
{
assert(head);
Node<int>* fast = head;
Node<int>* slow = head;
while (fast&&fast->_next)
{
fast = fast->_next->_next;
slow = slow->_next;
if (fast == slow) //有交点的话 说明有环
return make_pair(fast, true);
}
//不带环,直接返回
return make_pair(fast, false);
}
2.若带环求环的长度?
根据上一答案求出交点时,将环遍历一遍即可;
int length(Node<int>* head)
{
assert(head);
if (!IsExitsLoop(head).second)
return 0;
Node<int>* node=IsExitsLoop(head).first;
Node<int>* cur = node->_next;
int count = 1;
while (cur != node)
{
count++;
cur = cur->_next;
}
return count;
}
3.若带环求环的入口点
假设链表总长为L,头节点到入口点的距离为a,入口点到快慢指针交点距离为x,环的长度为r,现在假设慢指针走了S步与快指针相遇,
s = a + x;
那么快指针走了2S步,
2s = a + nr + x;
就可以得到:a + x = nr;
a = nr - x;
可以看出来,头节点到入口点的距离等于,交点到入口点的距离,那我们让两个指针,一个从交点走,一个从头节点走,最后一定在入口点相遇。
Node<int>* FindLoopPort(Node<int>* head)
{
assert(head);
Node<int>* node = IsExitsLoop(head).first;
Node<int>* cur = head;
while (cur != node)
{
cur = cur->_next;
node=node->_next;
}
return cur;
}