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

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
相关推荐
启观川7 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
longlongzihan9 小时前
链表找环:Floyd 判圈算法(LeetCode 141 & 142 )
c++·算法·leetcode·链表
Logic1019 小时前
C语言/数据结构欧几里得算法题解:长方形切割最大正方形——贪心划分计数
c语言·数据结构·算法·贪心算法·时间复杂度·空间复杂度·欧几里得算法
flinn_small11 小时前
三分算法:原理、实现与实战应用
数据结构·算法·三分
INGNIGHT12 小时前
944 · 最大子矩阵(前缀和)
数据结构·c++·算法
All for pursuit.12 小时前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
信奥卷王13 小时前
[GESP202609 六级] 数组划分
数据结构·算法
All for pursuit.14 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
殷色玫瑰17 小时前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
y1su18 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法