Leetcode una pregunta por día: 24.swap-nodes-in-pairs (intercambia nodos en la lista enlazada en pares)

Inserte la descripción de la imagen aquí
Idea: Recursividad o iteración, cada vez que usas tres nodos pre、now、nextpuedes lograr intercambio, principalmente por el intercambio de los dos primeros nodos de la lista enlazada (no disponible pre); lo
Inserte la descripción de la imagen aquí
extraño es que la recursividad e iteración ocupan casi el mismo espacio;

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

// 递归
// ListNode *swapPairs(ListNode *head)
// {
    
    
// 	if (head == nullptr)
// 	{
    
    
// 		return NULL;
// 	}
// 	if (head->next == nullptr)
// 	{
    
    
// 		return head;
// 	}
// 	ListNode *temp = head->next;
// 	head->next = temp->next;
// 	temp->next = head;
// 	fun(head->next, head);

// 	return temp;
// }

// void fun(ListNode *now, ListNode *pre)
// {
    
    
// 	if (now == nullptr || now->next == nullptr)
// 	{
    
    
// 		return;
// 	}
// 	ListNode *temp = now->next;
// 	now->next = temp->next;
// 	temp->next = now;
// 	pre->next = temp;
// 	fun(now->next, now);
// }

// 迭代
ListNode *swapPairs(ListNode *head)
{
    
    
	if (head == nullptr)
	{
    
    
		return NULL;
	}
	if (head->next == nullptr)
	{
    
    
		return head;
	}
	bool flag = true; //对链表前两个数进行交换,则不能用pre

	ListNode *now = head;
	ListNode *res = NULL;
	ListNode *pre = NULL;

	while (now != nullptr && now->next != nullptr)
	{
    
    
		//实现交换
		ListNode *temp = now->next;
		now->next = temp->next;
		temp->next = now;

		if (!flag) //非第一次交换,则需要pre连接到交换后的节点
		{
    
    
			pre->next = temp;
		}
		else
		{
    
    
			flag = false;
			res = temp;
		}
		
		pre = now;
		now = now->next;
	}
	return res;
}

Supongo que te gusta

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