Skip to content

LeetCode题解:24. 两两交换链表中的节点,递归,JavaScript,详细注释 #123

Open
@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

解题思路:

该题解实现了官方题解中的递归解法。

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function (head) {
  // 如果当前链表长度小于2,则直接返回当前节点。
  // 此处包括了链表长度为单数时,最后一次执行时,只有一个节点的情况。
  // 还包括了链表长度为双数时,最后一次执行,传入为null的情况
  if (!head || !head.next) {
    return head;
  }

  // 缓存要翻转的两个节点
  let firstNode = head;
  let secondNode = head.next;

  // 进行翻转
  // 假设此时链表为1->2->3->...,翻转节点1和2
  // firstNode将会指向后续的节点
  // 链表变为1->3->...,此时2依然指向3
  firstNode.next = swapPairs(secondNode.next);
  // secondNode指向firstNode
  // 链表变为2->1->3->...
  secondNode.next = firstNode;

  // 翻转完成后,secondNode变为了当前这段链表的头节点,可以返回给上一层的递归,作为上一层翻转时,firstNode.next的指向。
  return secondNode;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions