LeetCode.24两两交换链表中的节点

LeetCode.24两两交换链表中的节点

1.问题描述

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

复制代码
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

复制代码
输入:head = []
输出:[]

示例 3:

复制代码
输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目在范围 [0, 100]
  • 0 <= Node.val <= 100

2.解题思路

同样设置虚拟头结点,接下来就是交换相邻两个元素了,此时一定要画图,不画图,操作多个指针很容易乱,而且要操作的先后顺序

初始时,cur指向虚拟头结点,然后进行如下三步:

操作之后,链表如下:

看这个可能就更直观一些了:

切记要记录临时节点,因为如果不记录,某一步操作之后将会影响接下来的操作。

c 复制代码
ListNode* tmp = cur->next; // 记录临时节点
ListNode* tmp1 = cur->next->next->next; // 记录临时节点

3.代码

C++:

c 复制代码
#include <iostream>
#include <vector>
using namespace std;

// 定义链表节点结构
struct ListNode {
	int val;        // 节点存储的值
	ListNode* next; // 指向下一个节点的指针
	ListNode(int x) : val(x), next(NULL) {} // 构造函数
};

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
        ListNode* cur = dummyHead;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp = cur->next; // 记录临时节点
            ListNode* tmp1 = cur->next->next->next; // 记录临时节点

            cur->next = cur->next->next;    // 步骤一
            cur->next->next = tmp;          // 步骤二
            cur->next->next->next = tmp1;   // 步骤三

            cur = cur->next->next; // cur移动两位,准备下一轮交换
        }
        return dummyHead->next;
    }
};

// 根据一个整数数组创建链表
ListNode* createList(vector<int>& nums) {
	ListNode* head = NULL;
	ListNode* current = NULL;

	for (int i = 0; i < nums.size(); ++i) {
		if (head == NULL) {
			head = new ListNode(nums[i]);
			current = head;
		} else {
			current->next = new ListNode(nums[i]);
			current = current->next;
		}
	}
	return head;
}

// 打印链表中的元素
void printList(ListNode* head) {
	ListNode* cur = head; // 当前节点指针
	while(cur) {
		cout << cur->val << " "; // 打印当前节点值
		cur = cur->next;         // 移动到下一个节点
	}
	cout << endl; // 打印换行符
}

// 主函数
int main() {
	vector<int> nums; // 存储用户输入的整数数组
	int num;          // 用户输入的单个整数

	// 提示用户输入,以0结束
	cout << "Enter numbers for the list (0 to end): ";
	while (cin >> num && num != 0) {
		nums.push_back(num); // 将输入的数字添加到数组中
	}

	// 创建链表
	ListNode* head = createList(nums);

	// 打印交换前的链表
	cout << "Before reverse: ";
	printList(head);

	// 创建Solution类实例,并交换
	Solution sol;
	ListNode* newHead = sol.swapPairs(head);

	// 打印交换后的链表
	cout << "After reverse: ";
	printList(newHead);

	return 0; // 程序正常结束
}

python:

py 复制代码
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy_head = ListNode(next=head)
        current = dummy_head
        
        # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
        while current.next and current.next.next:
            temp = current.next # 防止节点修改
            temp1 = current.next.next.next
            
            current.next = current.next.next
            current.next.next = temp
            temp.next = temp1
            current = current.next.next
        return dummy_head.next
相关推荐
如意猴6 分钟前
双向链表----“双轨联动,高效运行” (第九讲)
数据结构·链表
帮帮志1 小时前
目录【系列文章目录】-(关于帮帮志,关于作者)
java·开发语言·python·链表·交互
Boop_wu2 小时前
[数据结构] Map和Set
java·数据结构·算法
要一起看日出2 小时前
数据结构------二叉查找树
数据结构·二叉查找树
小许学java8 小时前
数据结构-ArrayList与顺序表
java·数据结构·顺序表·arraylist·线性表
程序员莫小特11 小时前
老题新解|大整数加法
数据结构·c++·算法
小刘max12 小时前
深入理解队列(Queue):从原理到实践的完整指南
数据结构
蒙奇D索大13 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
洲覆13 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
MoRanzhi120313 小时前
15. Pandas 综合实战案例(零售数据分析)
数据结构·python·数据挖掘·数据分析·pandas·matplotlib·零售