LeetCode热题100-两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

复制代码
输入:head = [1,2,3,4]
输出:[2,1,4,3]

思路

  1. 新建虚拟头结点,简化头部交换逻辑
  2. cur 遍历,每次处理一组两个节点
  3. 设三组指针:first 当前第一个、second 当前第二个、nextPair 下一组起点
  4. 完成交换:cur→second→first→下一组
  5. cur 跳到 first,继续循环
python 复制代码
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        cur = dummy

        while cur.next and cur.next.next:
            first = cur.next
            second = cur.next.next
            next_p = second.next

            cur.next = second
            second.next = first
            first.next = next_p

            cur = first
        
        return dummy.next
相关推荐
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry1 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵2 小时前
【无标题】
数据结构·算法
Kx_Triumphs4 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎4 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀5 小时前
约瑟夫环问题
算法
科技大视界7 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴7 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe7 小时前
算法滑动窗口
数据结构·算法