【算法修炼-单链表】leetcode24.两两交换链表中的节点(js)

88 阅读1分钟

题目链接:leetcode-cn.com/problems/sw…

题目描述

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

示例1:

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

示例2:

输入: head = [1]
输出: [1]

解题

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    // 空节点或者只有一个节点
    if (head === null || head.next === null) return head;
    let node1 = head;
    let node2 = head.next;
    let node3 = node2.next;
    node2.next = node1;
    // 递归
    node1.next = swapPairs(node3);
    return node2;
};

总结

单链表要考虑边界条件,改变指针时记得保存,不能丟指针。

算法修炼github:github.com/mengmengzp/…