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

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
相关推荐
keep intensify39 分钟前
数据结构---单链表的增删查改
c语言·数据结构·c++·经验分享·学习·算法·分享
opple661 小时前
力扣-数据结构-二叉树
数据结构·算法·leetcode
时光话2 小时前
Lua 第14部分 数据结构
开发语言·数据结构·lua
我学上瘾了2 小时前
链表反转_leedcodeP206
网络·redis·链表
Phoebe鑫2 小时前
数据结构每日一题day13(链表)★★★★★
数据结构·链表
Seven973 小时前
缓存穿透的解决方式?—布隆过滤器
java·数据结构·redis
积极向上的向日葵3 小时前
链表的中间节点
数据结构·算法·链表·快慢指针
xin007hoyo10 小时前
算法笔记.染色法判断二分图
数据结构·笔记·算法
এ᭄画画的北北12 小时前
力扣-234.回文链表
算法·leetcode·链表
wuqingshun31415914 小时前
蓝桥杯 11. 打印大X
数据结构·算法·职场和发展·蓝桥杯·深度优先