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

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
相关推荐
7yewh7 小时前
SLAM 三维空间刚体运动(2)
数据结构·人工智能·机器人·嵌入式·slam
leikooo7 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
lvwangshu10 小时前
登录日志 题解
数据结构·线段树·题解·技巧·性质题·思维好题·细节题
CQU_JIAKE11 小时前
10.2【A】
数据结构
C++ 老炮儿的技术栈11 小时前
不一样的数值交换
数据结构·c++·人工智能·算法·c·csdn开发云
青山木12 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
梦帮科技13 小时前
vLLM / TensorRT-LLM 极限推理:PagedAttention 细粒度物理页表管理与连续批处理(Continuous Batching)实战
数据结构·人工智能·分布式·python·深度学习·算法·vllm
H.莓飛15 小时前
【数据结构】链表_OJ题
linux·数据结构·算法·链表
All for pursuit.15 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
7yewh18 小时前
SLAM 从视觉里程计到建图(6)
数据结构·人工智能·机器人·自动驾驶·嵌入式