Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swaping elements doubly linked list

I implement selecting sort and I need to swap elements. I have doubly linked list with previous and next links. And link to the first and last element in List I always need to swap some node b with first node toStartFrom

public void Swap(Node toStartFrom, Node b) {
        Boolean NextToEachOther = (toStartFrom.next == b);
        toStartFrom.next = b.next;
        b.previous = toStartFrom.previous;
        if (NextToEachOther) {
            toStartFrom.previous = b;
            b.next = toStartFrom;
        } else {
            toStartFrom.previous = b.previous;
            b.next = toStartFrom.next;
        }
    }

    public void display() {
        Node current = first;
        while (current != null) {
            ...printing...
            current = current.next;
        }
    }

But it doesn't work. No errors just doesn't sort in right order. And not diplays any elements after sort after toStartFrom node.

like image 263
Nikita Avatar asked Jun 11 '26 00:06

Nikita


1 Answers

You need to also update the nodes that are next to the 2 being swapped

For instance, consider this list:

first -> a -> b -> c

If you wish to swap first and b then you must also update a's and c's next and prev references.

Edit: This code should be placed before your code that does the swap and right after the Boolean declaration

Edit2: Also, if you have refences to the head/tail of the list, you need to update those too. I don't see that you referenced a head or tail anywhere in your code though.

if(toStartFrom.prev != null)
{
   toStartFrom.prev.next = b;
}
if(toStartFrom.next != b) // Equivalent to NextToEachOther
{
   toStartFrom.next.prev = b;
}
if(b.next != null)
{
   b.next.prev = toStartFrom;
}
if(b.prev != toStartFrom)  // Equivalent to NextToEachOther
{
   b.prev.next = toStartFrom
}
like image 79
Akron Avatar answered Jun 13 '26 12:06

Akron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!