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

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
相关推荐
1白天的黑夜11 小时前
链表-24.两两交换链表中的结点-力扣(LeetCode)
数据结构·leetcode·链表
养成系小王7 小时前
四大常用排序算法
数据结构·算法·排序算法
闪电麦坤959 小时前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤959 小时前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
球king9 小时前
数据结构中邻接矩阵中的无向图和有向图
数据结构
野渡拾光10 小时前
【考研408数据结构-05】 串与KMP算法:模式匹配的艺术
数据结构·考研·算法
pusue_the_sun18 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
liang_jy1 天前
数组(Array)
数据结构·面试·trae
要做朋鱼燕1 天前
【数据结构】用堆解决TOPK问题
数据结构·算法
秋难降1 天前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法