java - 仅使用指针的 Java 交换方法
问题描述
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 的列表来尝试交换索引值和下一个值。问题是我不能只做智能“切换值”的事情。我必须切换指针,但您可能会看到它拒绝正确切换
我还没有找到任何人处理相邻交换 2 个值并且无法使用值的组合
更新:一些修复。它根据打印完美地切换节点。问题是我仍然无法保存打印输出 print 1,3,2,4
解决方案
我假设“索引值”是当前值,“下一个值”是 current.next,
原理是使用current的parent。
对于第一个元素,您需要保存列表第一个元素的特殊变量——我称之为开始。为了澄清以后你有:
列表 -> item0-> item1 -> item2 -> ...
这里的第一个变量“list”是“head”或“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;
}
推荐阅读
- javascript - 我可以通过 javascript 将元标记注入 html 吗?当我这样做时有什么影响吗?
- python - 如何在python中读取带有变量的文件名?
- python-3.x - 我们如何使用 BeautifulSoup 和 Python 抓取缩小的 HTML?
- java - Open Route Service optimization api:如何向 api 发送最大行程时间
- python - 在python中除以两个数组的乘积时意外除以零错误
- java - Kryonet BufferOverFlow 异常
- database - 由于 1 个数据库上的锁定问题,具有多个数据库的 Postgres 实例是否会在多个/所有数据库中被阻止?
- php - 使用 laravel8 路由以形式传递参数
- node.js - 使用 typescript 编译和 Jest 发出运行节点
- javascript - jQuery按属性对不同的类元素进行排序