0

Hi I am trying to find out a way to swap two nodes in an unordered linked list. I want to find out a way where i can change the links of the two nodes so they are swapped. I know I am supposed to use the previous and next links as a way to swap them but I've tried a lot and I don't understand the algorithm. This is what I did so far, but it just deletes the node instead of swapping it and sometimes gives me a java heap error.

```
public void swap (int idx1, int idx2){ //error
Node node1prev;
Node node2prev;
Node tmp;
node1prev = this.getNode(idx1).prev;
node2prev = this.getNode(idx2).prev;
tmp = this.getNode(idx2).next;
if (this.getNode(idx1).next == this.getNode(idx2))
{
this.getNode(idx2).next = this.getNode(idx1);
this.getNode(idx1).next = tmp;
}
else
{
this.getNode(idx2).next = this.getNode(idx1).next;
this.getNode(idx1).next = tmp;
this.getNode(idx2).prev.next = this.getNode(idx1);
}
}
```

can someone please help? I want to swap the nodes, not the data within because I've already done that and it's easy to do, but I want to find a way to actually change the links of both nodes so the nodes swap altogether.

Thanks!