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

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
相关推荐
Jayden_Ruan6 小时前
C++十进制转二进制
数据结构·c++·算法
Haooog6 小时前
98.验证二叉搜索树(二叉树算法题)
java·数据结构·算法·leetcode·二叉树
lixinnnn.8 小时前
贪心:火烧赤壁
数据结构·c++·算法
前端 贾公子9 小时前
《Vuejs设计与实现》第 5 章(非原始值响应式方案)下 Set 和 Map 的响应式代理
数据结构·算法
快乐是一切9 小时前
PDF底层格式之水印解析与去除机制分析
前端·数据结构
MHJ_10 小时前
Multi-Metric Integration(多指标集成)
数据结构
小马学嵌入式~11 小时前
堆排序原理与实现详解
开发语言·数据结构·学习·算法
_给我学起来11 小时前
数据结构:树
数据结构
LGL6030A15 小时前
数据结构学习(2)——多功能链表的实现(C语言)
数据结构·学习·链表
nsjqj15 小时前
数据结构:栈和队列
数据结构