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

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

# 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

相关推荐

  1. 交换节点

    2024-01-12 14:40:03       57 阅读
  2. leetcode24. 交换节点

    2024-01-12 14:40:03       66 阅读
  3. LC24. 交换节点

    2024-01-12 14:40:03       69 阅读
  4. LeetCode [24] 交换节点

    2024-01-12 14:40:03       67 阅读
  5. 【Leetcode】24. 交换节点

    2024-01-12 14:40:03       64 阅读
  6. LeetCode24.交换节点

    2024-01-12 14:40:03       66 阅读
  7. 交换节点

    2024-01-12 14:40:03       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 14:40:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 14:40:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 14:40:03       82 阅读
  4. Python语言-面向对象

    2024-01-12 14:40:03       91 阅读

热门阅读

  1. 使用OTB数据集需要注意的一个问题

    2024-01-12 14:40:03       60 阅读
  2. Pandas实战100例 | 案例 19: 基本数学运算

    2024-01-12 14:40:03       53 阅读
  3. 安卓之缓存的应用场景以及各种技术优劣分析

    2024-01-12 14:40:03       54 阅读
  4. 组件v-model

    2024-01-12 14:40:03       57 阅读
  5. Spring Boot自定义启动Banner在线生成工具

    2024-01-12 14:40:03       48 阅读
  6. Vue实现输入框某一行高亮

    2024-01-12 14:40:03       64 阅读
  7. MySQL 中的 distinct 和 group by 哪个效率更高?

    2024-01-12 14:40:03       52 阅读
  8. Spring 容器的初始化过程

    2024-01-12 14:40:03       50 阅读