📝Leetcode 24. 两两交换链表中的节点

110 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

题目🌵

📝Leetcode 24. 两两交换链表中的节点

✏️leetcode-cn.com/problems/sw…


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

示例 1:

img

输入:head = [1,2,3,4]
输出:[2,1,4,3]

解题思路💡

递归

  • 直接就是两两交换
var swapPairs = function (head) {
    if (head == null || head.next == null) {
        return head
    }
    const newHead = head.next
    head.next = swapPairs(newHead.next)
    newHead.next = head
    return newHead
};

迭代

image.png

(图来自 猿来绘)

  • 首先定义一个虚拟节点

  • 定义临时节点保存当前节点,下一节点,下下节点的信息

  • 如图所示,将 12 =>14,13 =>15,14=>13

var swapPairs = function (head) {
    const dummyHead = new ListNode(0, head)
    let cur = dummyHead
    while (cur.next && cur.next.next) {
        // 临时节点  保存节点信息
        let tmp = cur
        let tmp1 = tmp.next
        let tmp2 = tmp1.next
        // 将两个头元素指向变换后的节点
        tmp.next = tmp2
        tmp1.next = tmp2.next
        tmp2.next = tmp1
        // 移动位置
        cur = cur.next.next
    }
    return dummyHead.next
};

image-20220407165624288