我用谷歌搜索了这个,但他们都在谈论“交换节点而不交换数据”。我尝试自己编写一个交换节点方法:public void swapNodes(int num1, int num2) { if(num1 == num2) { return; } Node currentNum1 = head; Node currentNum2 = head; Node waitForSwap1 = null; Node waitForSwap2 = null; while (currentNum1 != null) { if (currentNum1.data == num1) { waitForSwap1 = currentNum1; System.out.println(); System.out.println("waitForSwap 1"); System.out.println(waitForSwap1.data); } currentNum1 = currentNum1.next; } while (currentNum2 != null) { if (currentNum2.data == num2) { waitForSwap2 = currentNum2; System.out.println("waitForSwap 2"); System.out.println(waitForSwap2.data); } currentNum2 = currentNum2.next; } currentNum1 = waitForSwap2; currentNum2 = waitForSwap1; System.out.println("currentNum1"); System.out.println(currentNum1.data); System.out.println("currentNum2"); System.out.println(currentNum2.data);}这是结果如您所见,currentNum1并currentNum2相互更改,但打印结果没有交换。如何交换两个节点及其数据?
1 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
好的,如果你只想交换数据,而不是节点,这里是:
public void swapNodes(int num1, int num2) {
if (num1 == num2) {
return;
}
Node node1 = null;
Node node2 = null;
Node cur = head;
while(cur != null) {
if (num1 == cur.data) {
node1 = cur;
}
if (num2 == cur.data) {
node2 = cur;
}
cur = cur.next;
}
if (node1 == null || node2 == null)
return;
int tmp = node1.data;
node1.data = node2.data;
node2.data = tmp;
}
添加回答
举报
0/150
提交
取消