📌  相关文章
📜  用于在链接列表中从开始到结束第 K 个节点交换第 K 个节点的 Javascript 程序(1)

📅  最后修改于: 2023-12-03 14:56:20.191000             🧑  作者: Mango

用于在链接列表中从开始到结束第 K 个节点交换第 K 个节点的 Javascript 程序

在编写链表操作代码时,可能需要对链表中的节点进行交换。本文将介绍如何使用 Javascript 程序在链接列表中从开始到结束第 K 个节点交换第 K 个节点。

问题描述

在链表中,我们需要交换第 K 个节点和第 K 个节点(两个节点在同一位置)。例如,在以下链表中:

1 -> 2 -> 3 -> 4 -> null

如果 K 为 2,则需要将第二个节点和第二个节点交换,即将上面的链表变为:

1 -> 3 -> 2 -> 4 -> null
解决方案

要解决这个问题,可以使用三个指针,prev,curr 和 next,其中 prev 是第 K-1 个节点的指针,curr 是第 K 个节点的指针,next 是第 K+1 个节点的指针。通过移动这些指针,可以将第 K 个节点和第 K+1 个节点交换。这里是实现该解决方案的 Javascript 程序:

function swapNodes(head, K) {
  let count = 0;
  let curr = head;
  let prev = null;
  let next = null;

  // Find the Kth node and its previous node
  while (curr !== null && count < K) {
    prev = curr;
    curr = curr.next;
    count++;
  }

  // If K is greater than the length of the linked list, return the original linked list
  if (curr === null) {
    return head;
  }

  // Store the next node of Kth node
  next = curr.next;

  // Reverse the pointers of Kth and (K+1)th node
  curr.next = next.next;
  next.next = curr;

  // Change the pointers of (K-1)th node and Kth node
  if (prev !== null) {
    prev.next = next;
  } else {
    head = next;
  }

  return head;
}
程序说明

该程序使用几个变量来实现链表节点的交换。以下是每个变量的说明:

  • head:链接列表的头。
  • count:循环计数器。
  • curr:当前节点。
  • prev:前一个节点。
  • next:下一个节点。

以下是每个逻辑步骤的说明:

  1. 从头开始循环列表,直到 curr 是第 K 个节点,同时记录 prev。
  2. 如果 curr 已经是 null(列表长度小于 K),则返回原始列表。
  3. 存储第 K 个节点的下一个节点。
  4. 反转第 K 个节点和第 K+1 个节点的指针。
  5. 更改第 K-1 个节点和第 K 个节点的指针,以指向第 K+1 个节点。
  6. 返回修改后的列表头。
使用示例

以下是使用该函数的示例代码:

const LinkedList = require('./LinkedList');

const list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.append(4);

console.log(list.toString()); // Output: 1 -> 2 -> 3 -> 4 -> null

const newHead = swapNodes(list.head, 2);

list.head = newHead;
console.log(list.toString()); // Output: 1 -> 3 -> 2 -> 4 -> null
复杂度

该函数的时间复杂度为 O(K),其中 K 是要交换的节点的位置。这是因为我们只需要循环 K 次,以便找到前 K 个节点。

空间复杂度为 O(1),因为我们只需要使用固定数量的指针来执行节点交换操作。