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

猜你喜欢

转载自blog.csdn.net/qq_35683407/article/details/105837293