简体   繁体   中英

Swapping two adjacent nodes in a linked list java

I have a very trivial problem, what should be a matter of just changing links. I've read a few answers, and some show how to do this by swapping the data, and some give a vague explanation of the concept.

Here's the method that seems to be running me in circles. When I swap the target node to the previous node, the node is simply skipped. Then when I go back to reference the next node, I get stuck in an eternal loop. I need to know If I need another node traversing from the head, or if I can simply reference the new link. I know I'm missing something quite obvious.

for (cursor = head; cursor != null; cursor = cursor.link) {
  if (target == cursor.data) {
    Target = cursor.link.getLink();
    next = cursor.getLink();
    prev = cursor;
    System.out.println(prev.getData()); // for testing
    System.out.println(next.getData());
    prev.setLink(Target); // Swaps the first link
    //Target.setLink(prev); // causes eternal loop
  }}
  return Target.getData();
}

This is my testing method, creating a list of 7 nodes, and printing to the screen.

public static void main(String[] args) {
  SLL LL = new SLL(18, null);

  LL.add(4);
  LL.add(14);
  LL.add(8);
  LL.add(12);
  LL.add(2);
  LL.add(28);
  System.out.println(LL.toString());
  System.out.println(LL.swap(12));
  System.out.println(LL.toString());
}

This is the output I get:

{18, 28, 2, 12, 8, 14, 4}

12

8

14

{18, 28, 2, 12, 14, 4}

Desired output would be:

{18, 28, 2, 12, 8, 14, 4}

{18, 28, 2, 8, 12, 14, 4}

It looks like you're trying to swap a specific node (determined by the value of the node) with the node after it?.

The easiest solution to the problem you presented is to just swap the values, instead of trying to swap the nodes.

Something like this should work since you're dealing with primitives

if(currNode.value() == targetValue) {
   Node nextNode = currentNode.next();
   currentNode.setValue(nextNode.getValue()); //set the current node's value to the next node's value
   nextNode.setValue(targetValue);
}

Just be sure to handle the case where your target value is in the last node in the list.

Edit- since for some reason you want to change the links instead, the general logic is-

  • keep track of 3 nodes: prev, current, next
  • set prev.link = next
  • set current.link = next.link
  • set next.link = current

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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