gpt4 book ai didi

java - 交换循环链表节点

转载 作者:行者123 更新时间:2023-11-30 11:55:30 25 4
gpt4 key购买 nike

基本上我必须将循环链表中的一组节点移动到同一链表中的不同位置。

      prev  ptr

[1]-->[2]-->[3]-->[4]
<--------------------
假设我想在 3 和 4 之间移动 1 和 2,然后让 4 圈回到 3。我有指向 1 (temp1)、3 (temp3) 和 4 (temp4) 的临时指针。我认为这些是操作的重要指针,因此我为它们设置了温度。

如何设置 prev 和 ptr 指针以与 temp 指针协调?这非常令人困惑,我将任何组合放在一起并尝试打印列表,它会让我陷入无限循环。我想了解一种精确的接近方法这。谢谢。

最佳答案

将操作视为两个不同的操作可能更容易。删除,然后插入。

// remove the node
Node node = ...; // whatever identifies the node to operate on
prev(node).setNext(next(node));

// insert it into its new position
Node newPrev = ...; // whatever identifies the node to operate on
Node newNext = newPrev.next();
newPrev.setNext(node);
node.setNext(newNext);

关于java - 交换循环链表节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com