简体   繁体   English

交换元素双重链表

[英]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 链接到List I中的第一个和最后一个元素我总是需要将一个节点b与第一个节点交换到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. 并且在toStartFrom节点之后排序后不会覆盖任何元素。

You need to also update the nodes that are next to the 2 being swapped 您还需要更新被交换的2旁边的节点

For instance, consider this list: 例如,请考虑以下列表:

first -> a -> b -> c 首先 - > 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. 如果您希望先交换b,那么您还必须更新a和c的next和prev参考。

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. Edit2:另外,如果你已经重新添加到列表的头部/尾部,你也需要更新它们。 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
}

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

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