简体   繁体   English

交换链表中的节点 java

[英]swap nodes from a linked list java

I am trying to swap two nodes from given positions from a linked list, I currently have done this but nothing is being swapped and I also have to make sure to print an error if they pick a position that is not on the linked list for example there are 5 nodes so if a position is 6 it should print an error where can I put that message.我正在尝试从链表中的给定位置交换两个节点,我目前已经完成了这个但是没有任何东西被交换并且我还必须确保打印错误如果他们选择一个不在链表中的 position 例如有 5 个节点,所以如果 position 是 6,它应该打印一条错误消息,我可以在哪里放置该消息。 The method can't be changed from the way it is方法无法改变

void swapping(int a, int b){
POI curr1;
POI temp = head;
POI temp1;
int i = 1;
POI temp2;
POI curr2;
while(i < a - 1){
  temp= temp.next;
  i++;
}
temp1 = temp;
curr1 = temp1.next;

while(i < b - 1){
  temp= temp.next;
  i++;
}
temp2 = temp;
curr2 = temp2.next;

temp = curr1.next;
temp2.next = curr1;
curr1.next = curr2.next;

you should read about "pass by reference" vs "pass by value" in java, primitives (in your case int a, int b ) are passed by value - meaning java makes a copy of those values, and once method exits - those values no longer exists.您应该阅读 java 中的“按引用传递”与“按值传递”,基元(在您的情况下int a, int b )按值传递 - 意味着 java 复制这些值,一旦方法退出 - 这些值不复存在。

so technically you can't void swap (int a, int b) you'll need a wrapper for that.所以从技术上讲你不能void swap (int a, int b)你需要一个包装器。 (indeed there are boxed primitives eg - Integer , but they also won't work in this case because they are immutable) (确实有盒装基元,例如 - Integer ,但在这种情况下它们也不起作用,因为它们是不可变的)

you should do something like:你应该这样做:

 class IntWrapper {
   int value
 }
 
 void swap(IntWrapper a, IntWrapper b) {
   int temp = a.value;
   a.value = b.value;
   b.value = temp.value;
 }

because IntWrapper is an Object it is passed by reference因为IntWrapper是一个Object它是通过引用传递的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM