c++算法 判断单链表是否有环 环的结点位置

判断单链表是否有环思路很简单,一个指针走一步一个指针走两步,如果有环则最终会相遇

判断环的位置,在有环的基础上,环节点会有两个指针指向它

struct Node
{
	int value;
	struct Node* next;
	int in;  //被指向次数
	Node(int v) :value(v),in(0){};
};


bool isCircle(Node* head)
{
	Node* first = head, *second = head;
	while (first->next != nullptr && second->next->next != nullptr)
	{
		first = first->next;
		second = second->next->next;
		if (first == second)
		{
			return true;
		}
	}
	return false;
}


Node* findCircle( Node* head)
{
	Node* first = head;
	Node* second = head;
	while ( first->next->in != 2)
	{
		++(first->next->in);
		first = first->next;
	}
	cout << first->next->value << endl;
	return first->next;
}

猜你喜欢

转载自blog.csdn.net/yufanghu/article/details/80989583