📌  相关文章
📜  用于就地重新排列给定链接列表的 Javascript 程序

📅  最后修改于: 2022-05-13 01:57:44.311000             🧑  作者: Mango

用于就地重新排列给定链接列表的 Javascript 程序

给定一个单链表 L 0 -> L 1 -> ... -> L n-1 -> L n 。重新排列列表中的节点,使新形成的列表为: L 0 -> L n -> L 1 -> L n-1 -> L 2 -> L n-2
您需要在不更改节点值的情况下就地执行此操作。

例子:

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

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

简单的解决方案:

1) Initialize current node as head.
2) While next of current node is not null, do following
    a) Find the last node, remove it from the end and insert it as next
       of the current node.
    b) Move current to next to next of current

上述简单解决方案的时间复杂度为 O(n 2 ),其中 n 是链表中的节点数。

更好的解决方案:
1) 将给定链表的内容复制到向量。
2)通过交换两端的节点来重新排列给定的向量。
3) 将修改后的向量复制回链表。
这种方法的实施:https://ide.geeksforgeeks.org/1eGSEy
感谢 Arushi Dhamija 提出这种方法。

高效解决方案:

1) Find the middle point using tortoise and hare method.
2) Split the linked list into two halves using found middle point in step 1.
3) Reverse the second half.
4) Do alternate merge of first and second halves.

该解决方案的时间复杂度为 O(n)。

下面是这个方法的实现。

Javascript


Javascript


Javascript


输出:

1 -> 2 -> 3 -> 4 -> 5 
1 -> 5 -> 2 -> 4 -> 3

时间复杂度: O(n)
辅助空间: O(1)
感谢 Gaurav Ahirwar 提出上述方法。

另一种方法:
1.取两个指针prev和curr,分别保存head和head->next的地址。
2.比较他们的数据并交换。
之后,形成一个新的链表。

下面是实现:

Javascript


输出:

6 9 3 8 7

时间复杂度: O(n)
辅助空间: O(1)
感谢 Aditya 提出这种方法。

另一种方法:(使用递归)

  1. 持有指向头节点的指针并使用递归直到最后一个节点
  2. 到达最后一个节点后,开始将最后一个节点交换到头节点的下一个节点
  3. 将头指针移动到下一个节点
  4. 重复此操作,直到头部和最后一个节点相遇或彼此相邻
  5. 一旦满足停止条件,我们需要丢弃左节点以修复在交换节点时在列表中创建的循环。

Javascript


输出:

1 ->2 ->3 ->4 ->5 
1 ->5 ->2 ->4 ->3

请参阅有关就地重新排列给定链接列表的完整文章。更多细节!