Leetcode una pregunta del día: 142.linked-list-cycle-ii (lista circular enlazada Ⅱ)

Inserte la descripción de la imagen aquí
Idea: método de círculo de juicio directo de Floyd
Inserte la descripción de la imagen aquí

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;
}

Supongo que te gusta

Origin blog.csdn.net/wyll19980812/article/details/109003855
Recomendado
Clasificación