Leetcode每日一题:142.linked-list-cycle-ii(环形链表Ⅱ)

在这里插入图片描述
思路:直接Floyd判圈法
在这里插入图片描述

struct ListNode
{
    
    
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {
    
    }
};

ListNode *detectCycle(ListNode *head)
{
    
    
	//floyd判圈法 先确定是否存在环
	if (head == NULL)
		return NULL;
	ListNode *f = head, *l = head;
	while (f->next)
	{
    
    
		f = f->next;
		if (f->next)
		{
    
    
			f = f->next;
			l = l->next;
			if (f == l)
			{
    
    
				break;
			}
		}
		else
		{
    
    
			break;
		}
	}

	if (f->next == NULL)
	{
    
    
		return NULL;
	}

	//如果存在环
	l = head;
	while (l != f)
	{
    
    
		l = l->next;
		f = f->next;
	}
	return f;
}

猜你喜欢

转载自blog.csdn.net/wyll19980812/article/details/109003855
今日推荐