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
相关推荐
qing_0406037 分钟前
数据结构——二叉搜索树
数据结构·c++·二叉树·二叉搜索树
yonuyeung26 分钟前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾32 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
mvufi2 小时前
day58 第十一章:图论part08
数据结构·算法·图论
醉城夜风~2 小时前
[数据结构]栈详解
数据结构
williamzhou_20132 小时前
深搜专题2:组合问题
数据结构·算法
YGGP2 小时前
【每日八股】Redis篇(二):数据结构
数据结构·数据库·redis
夏末秋也凉12 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
王老师青少年编程12 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
liuyuzhongcc15 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list