LeetCode142. Linked List Cycle||(环形链表)——— 判断链表是否有环以及求其入环节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ming991301630/article/details/83060097
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(nullptr) {}
};
//判断链表是否有环
//方法:
//1、空间复杂度n:使用set集合保存每一个节点,判断是否有重复
//2、空间复杂度1:使用两个指针,快指针走两步,慢指针走一步;
//				  若快指针为null则无环。
//				  若快指针与慢指针相遇,快指针回到开头与慢指针一起每次只走一步,直至相遇为入环节点。
class Solution {
public:
	ListNode * detectCycle(ListNode *head) {
		if (head == nullptr || head->next == nullptr)return nullptr;
		ListNode *fastp = head, *slowp = head;
		while (true)
		{
			if (fastp->next == nullptr || fastp->next->next == nullptr)return nullptr;//快指针为null则无环 + 防止访问到空指针
			fastp = fastp->next->next;
			slowp = slowp->next;
			if (slowp == fastp)break;//快指针与慢指针相遇,则有环
		}
		fastp = head;
		while (fastp != slowp)
		{
			fastp = fastp->next;
			slowp = slowp->next;
		}
		return slowp;
	}
};

猜你喜欢

转载自blog.csdn.net/Ming991301630/article/details/83060097
今日推荐