Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Aug 7, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接: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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant