gpt4 book ai didi

仅使用指针的 Java 交换方法

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

public void swap(int index)
{
//If the index = 0, then swap 0 and 1, if 10 is given, swap 10 and 11.
Node current = start;

for(int i = 0; i < index; i++)
{
current = current.next;
}

// = 2
Node temp = current;
// = 3
Node temp2 = current.next;

System.out.println("Temp = " + temp.value + " | Refernces to: " + temp);
System.out.println("Temp = " + temp2.value + " | Refernces to: " + temp2);
System.out.println();

System.out.println("Current is 3 and now we switching to 2 | Current: " + current.value);
System.out.println();
//2 then goes to 3
current = temp2;
System.out.println("Current must equal 3 | Current: " + current.value);
System.out.println();
//3 turns into 2
System.out.println("Current must equal 2 | Current: " + current.value);
System.out.println();

current = temp;

System.out.println("Now current is suppose to be 3: " + current.value);


System.out.println();

current = start;
while(current != null)
{
System.out.println(current.value + " | " + current);
current = current.next;
}

}

这使用 1,2,3,4 的列表尝试交换索引值和下一个值。问题是我不能只做智能“切换值”的事情。我必须切换指针,但正如您可能看到的那样,它拒绝正确切换

我还没有找到任何人处理彼此相邻交换两个值并且无法使用值的组合

更新:一些修复。它根据打印完美地切换节点。问题是我仍然无法保存打印输出 print 1,3,2,4

最佳答案

我假设“索引值”是当前值,“下一个值”是current.next,

原理是使用current的parent。

对于第一个元素,您需要一个特殊变量来保存列表的第一个元素 - 我称之为 start。为了澄清稍后你有:

列表 -> item0 -> item1 -> item2 -> ...

这里的第一个变量“列表”是“头”或“ anchor ”。您存储第一个元素的变量是头(或“ anchor ”),称为开始(就像在OP中一样)。

public void swap(int index) {
Node prev;
Node next;
Node current = start;
//special treatment, as the head changes!
if (0 == index) {
//define
next = current.next;
//do the swap
current.next = next.next;
next.next = current;
start = next; // the head changes!
return;
}
//stop one before the one you need to swap(index-1)
for (int i = 0; i < index - 1; i++) {
current = current.next;
System.out.println("Value is: " + current.value);
}
//define
prev = current;
current = prev.next;
next = current.next;
// do the swap:
prev.next = next;
current.next = next.next;
next.next = current;
}

关于仅使用指针的 Java 交换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526384/

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