Nikita
Nikita

Reputation: 325

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.

Upvotes: 4

Views: 2619

Answers (1)

Akron
Akron

Reputation: 1534

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
}

Upvotes: 2

Related Questions