给定链表的成对交换元素的 JavaScript 程序


在本教程中,我们将学习如何使用 JavaScript 编写真对交换给定链表元素的程序。链表上的一种常见操作是成对交换相邻元素。此操作在各种场景中都很有用,例如重新组织数据、按特定顺序重新排列元素或优化某些算法。此外,我们将重点关注使用 JavaScript 解决给定链表中成对交换元素的问题。我们将提供一个逐步实现算法的方法,解释其背后的逻辑和代码。在本教程结束时,您将清楚地了解如何实现一个 JavaScript 程序来成对交换链表中的元素,以及每个步骤的示例代码和解释。

让我们深入研究并探索 JavaScript 中此问题的解决方案!

问题陈述

给定一个链表,任务是实现一个 JavaScript 程序,该程序成对交换元素。换句话说,链表中连续位置的元素要相互交换。如果链表中的元素数量为奇数,则最后一个元素保持不变。程序应返回修改后的链表的头。

示例

示例 1

Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 2 -> 1 -> 4 -> 3 -> 5

说明 − 在给定的链表中,位置 1 和 2(1 和 2 是 0 索引)的元素被交换,结果为 2 -> 1 -> 3 -> 4 -> 5。然后,位置 3 和 4 的元素被交换,结果为 2 -> 1 -> 4 -> 3 -> 5。

示例 2

Input: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
Output: 20 -> 10 -> 40 -> 30 -> 60 -> 50 -> 70

说明在给定的链表中,位置 1 和 2 的元素被交换,结果为 20 -> 10 -> 30 -> 40 -> 50 -> 60 -> 70。然后,位置 3 和 4 的元素被交换,结果为 20 -> 10 -> 40 -> 30 -> 50 -> 60 -> 70。最后,位置 5 和 6 的元素被交换,结果为 20 -> 10 -> 40 -> 30 -> 60 -> 50 -> 70。

现在,让我们了解实现此问题陈述的算法。

算法

  • 创建一个名为 pairwiseSwap(head) 的函数,该函数将链表的头作为输入。

  • 初始化一个临时变量 temp 来存储当前节点,并将其设置为链表的头。

  • 以 2 为步长遍历链表,即一次移动两个节点。

  • 对于每一对节点,交换它们的值。

  • 移动到下一对节点。

  • 继续此过程,直到到达链表的末尾或没有更多要交换的节点对。

  • 返回修改后的链表的头。

因此,在了解算法之后,让我们借助一个示例来实现此算法,在该示例中,我们将借助 JavaScript 来实现此算法。

示例:使用 JavaScript 实现

上面的程序实现了给定链表中元素的成对交换。它使用 Node 类来表示链表的节点,并使用 pairwiseSwap() 函数来成对交换相邻节点的值。程序首先创建一个具有给定元素集的链表,显示原始链表,使用 pairwiseSwap() 函数执行成对交换,然后显示具有交换元素的更新后的链表。

输入:原始链表:1 -> 2 -> 3 -> 4 -> 5 -> null

预期输出:成对交换后的链表:2 -> 1 -> 4 -> 3 -> 5 -> null

class Node {
   constructor(value) {
      this.value = value;
      this.next = null;
   }
}
function pairwiseSwap(head) {
   let temp = head;
   while (temp !== null && temp.next !== null) {
      // Swap values of current and next nodes
      let tempVal = temp.value;
      temp.value = temp.next.value;
      temp.next.value = tempVal;
      // Move to the next pair of nodes
      temp = temp.next.next;
   }
   return head;
}

// Linked list with odd number of elements
let head = new Node(1);
let node2 = new Node(2);
let node3 = new Node(3);
let node4 = new Node(4);
let node5 = new Node(5);
head.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
console.log("Original Linked List:");
let temp = head;
while (temp !== null) {
   process.stdout.write(temp.value + " -> ");
   temp = temp.next;
}
console.log("null");
head = pairwiseSwap(head);
console.log("Linked List after Pairwise Swapping:");
temp = head;
while (temp !== null) {
   process.stdout.write(temp.value + " -> ");
   temp = temp.next;
}
console.log("null");

结论

总而言之,本教程中提供的 JavaScript 程序演示了给定链表中元素成对交换的有效解决方案。该算法迭代链表,成对交换相邻元素,从而得到一个具有交换元素的更新后的链表。此解决方案在需要在链表操作中交换元素的各种场景中都很有用。通过实现此程序,可以轻松地使用 JavaScript 成对交换链表中的元素。

更新于:2023年5月2日

浏览量 180

启动您的 职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.