1日に1つの質問をLeetcodeします:24.swap-nodes-in-pairs(リンクされたリストのノードをペアで交換します)

ここに写真の説明を挿入
アイデア:再帰または反復。3つのノードを使用するたびにpre、now、next、主にリンクリストの最初の2つのノードの交換(使用不可pre)で交換を実行できます
ここに写真の説明を挿入
奇妙なことに、再帰と反復はほぼ同じスペースを占有します。

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

おすすめ

転載: blog.csdn.net/wyll19980812/article/details/109071809