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

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
相关推荐
库玛西4 小时前
攻克 408 数据结构:图论基石深度拆解(数学极值推演 + 存储内存剖析 + BFS/DFS 双核模板)
数据结构·算法·深度优先·广度优先·图搜索算法
m0_547486666 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr6 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_36 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.6 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.6 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣6 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9926 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王6 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水6 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp