力扣24. 两两交换链表中的节点(迭代)

力扣24. 两两交换链表中的节点(迭代)

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

 

把链表分为两部分,即奇数节点为一部分,偶数节点为一部分,firstnode 指的是交换节点中的前面的节点,secondnode 指的是要交换节点中的后面的节点。在完成它们的交换,我们还得用 left记录 A 的前驱节点。

复杂度分析

  • 时间复杂度:O(N),其中 N 指的是链表的节点数量。
  • 空间复杂度:O(1)。
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}

};

class Solution
{
public:
	ListNode* swapPairs(ListNode* head)
	{
		while (head == nullptr)return head;
		ListNode* tou = new ListNode(0);
		tou->next = head;
		//left指针是标记交换节点的前一个指针
		ListNode* left = tou;
		//交换,记住改变的是节点,所以要对head操作不能只是指针改变
		while (head != nullptr && head->next != nullptr)
		{
			//调换firstnode和secondnode
			ListNode* firstnode = head;
			ListNode* secondnode = head->next;
			
			//交换
			left->next = secondnode;
			firstnode->next = secondnode->next;
			secondnode->next = firstnode;

			//循环,指针下移
			head = firstnode->next;
			left = firstnode;
		}
		return tou->next;
	}
};

int main()
{
	Solution s;
	ListNode head[5] = { 1,2,3,4,5 };
	head[0].next = &head[1];
	head[1].next = &head[2];
	head[2].next = &head[3];
	//head[3].next = &head[4];
	ListNode* out1 = head;
	while (out1)
	{
		cout << out1->val << '\t';
		out1 = out1->next;
	}
	cout << '\n';
	auto result1 = s.swapPairs(head);
	ListNode* out2 = result1;
	while (out2)
	{
		cout << out2->val << '\t';
		out2 = out2->next;
	}
	cout << '\n';
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值