Skip to content
本页目录

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

题目描述

题目描述

  • 给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。

  • 你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

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

思路

思路

  • 如果链表为空或链表只有一个节点,则无需交换,直接返回头节点。
  • 创建一个虚拟头节点 dummyHead 指向头结点,再定义 current 节点指向虚拟头节点 dummyHead
  • current.next 和 current.next.next 都不为空的时候,执行交换操作。
  • 具体交换规则见代码

代码

js
/**
 * 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 || !head.next) {
    return head;
  }
  // 创建一个虚拟头结点
  const dummyHead = new ListNode(0);
  dummyHead.next = head;
  let current = dummyHead;

  // 遍历链表,交换相邻节点
  while (current.next !== null && current.next.next !== null) {
    const first = current.next;
    const second = current.next.next;

    // 交换相邻节点
    first.next = second.next;
    second.next = first;
    current.next = second;

    // 移动到下一组相邻节点的前一个节点
    current = current.next.next;
  }
  // 返回交换后的链表头结点
  return dummyHead.next;
};

MIT Licensed