两两交换链表中的节点【链表】

Problem: 24. 两两交换链表中的节点

文章目录

思路 & 解题方法

假如要交换1号节点和2号节点:

0->1->2->3变成

0->2->1->3就行了。

复杂度

时间复杂度:

O ( n ) O(n) O(n)

空间复杂度:

O ( 1 ) O(1) O(1)

Code

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node0 = ans = ListNode(0, head)
        node1 = head
        while node1 and node1.next:
            node2 = node1.next
            node3 = node2.next
            # 0->1->2->3
            node0.next = node2
            node2.next = node1
            node1.next = node3
            # 0->2->1->3
            node0 = node1
            node1 = node3
        
        return ans.next
相关推荐
ambition2024211 分钟前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
代码旅人ing22 分钟前
链表算法刷题指南
数据结构·算法·链表
不爱吃炸鸡柳2 小时前
单链表专题(完整代码版)
数据结构·算法·链表
Morwit2 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
田梓燊5 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
葳_人生_蕤6 小时前
hot100——栈和队列
数据结构
历程里程碑7 小时前
二叉树---二叉树的中序遍历
java·大数据·开发语言·elasticsearch·链表·搜索引擎·lua
Meme Buoy8 小时前
18.补充数学1:生成树-最短路径-最大流量-线性规划
数据结构·算法
汀、人工智能8 小时前
[特殊字符] 第89课:岛屿数量
数据结构·算法·数据库架构·图论·bfs·岛屿数量
九英里路8 小时前
cpp容器——string模拟实现
java·前端·数据结构·c++·算法·容器·字符串