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

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
相关推荐
xiaoye-duck6 小时前
计数排序:高效非比较排序解析
数据结构
稚辉君.MCA_P8_Java7 小时前
通义 插入排序(Insertion Sort)
数据结构·后端·算法·架构·排序算法
无限进步_8 小时前
C语言动态内存的二维抽象:用malloc实现灵活的多维数组
c语言·开发语言·数据结构·git·算法·github·visual studio
Swift社区8 小时前
LeetCode 432 - 全 O(1) 的数据结构
数据结构·算法·leetcode
芬加达8 小时前
leetcode34
java·数据结构·算法
leoufung9 小时前
链表题目讲解 —— 删除链表的倒数第 n 个节点(LeetCode 19)
数据结构·leetcode·链表
dragoooon349 小时前
[优选算法专题八.分治-归并 ——NO.46~48 归并排序 、数组中的逆序对、计算右侧小于当前元素的个数]
数据结构·算法·排序算法·分治
招摇的一半月亮9 小时前
P2242 公路维修问题
数据结构·c++·算法
JHC0000009 小时前
交换链表中的节点
数据结构·链表