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
相关推荐
鱼跃鹰飞1 天前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
好评1241 天前
【C++】二叉搜索树(BST):从原理到实现
数据结构·c++·二叉树·二叉搜索树
程序猿炎义1 天前
【Easy-VectorDB】Faiss数据结构与索引类型
数据结构·算法·faiss
jiaguangqingpanda1 天前
Day24-20260120
java·开发语言·数据结构
52Hz1181 天前
力扣24.两两交换链表中的节点、25.K个一组反转链表
算法·leetcode·链表
老鼠只爱大米1 天前
LeetCode经典算法面试题 #160:相交链表(双指针法、长度差法等多种方法详细解析)
算法·leetcode·链表·双指针·相交链表·长度差法
ValhallaCoder1 天前
Day53-图论
数据结构·python·算法·图论
C雨后彩虹1 天前
羊、狼、农夫过河
java·数据结构·算法·华为·面试
Elastic 中国社区官方博客1 天前
使用瑞士风格哈希表实现更快的 ES|QL 统计
大数据·数据结构·sql·elasticsearch·搜索引擎·全文检索·散列表
重生之后端学习1 天前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展