24 - Swap Nodes in Pairs

本文介绍了一种链表节点成对交换的算法实现,通过引入哑节点简化处理流程,避免了对头节点特殊处理的问题。文章提供了详细的代码示例及步骤说明。

不说废话,先贴上代码

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

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

class Solution_024_SwapNodesinPairs
{
public:
	ListNode* swapPairs(ListNode* head) 
	{
		if (head == nullptr || head->next == nullptr)
		{
			return head;
		}

		ListNode dummy(-1);
		dummy.next = head;

		for (ListNode *prev = &dummy, *cur = prev->next, *next = cur->next; next; prev = cur, cur = cur->next, next = cur? cur->next:nullptr)
		{
			prev->next = next;
			cur->next = next->next;
			next->next = cur;
		}

		return head->next;
	}
};
分析过程:

本体设置了dummy结点,因为有了dummy之后,所有的节点都变成拥有前置节点的节点了。所以就不用担心处理头节点这个特殊情况了。

初始状态:



经过第一轮循环后,


实际上节点的顺序是:已经交换了头两个结点的顺序了


根据for循环的第三个条件

prev = cur, cur = cur->next,  next = cur? cur->next:nullptr


以此类推




评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值