【问题标题】:Doubly Linked List node swapping issue双链表节点交换问题
【发布时间】:2013-10-15 07:56:22
【问题描述】:

我正在尝试通过节点结构 (age) 中的 int 值重新排序我的 DLL。当我直接访问 int 时它可以工作,但我试图交换整个节点,这样当列表重新排序时我就不必交换结构中的每个变量。

void DLL::ReOrg(node* head, int DLL_Size)
{

node* temp = head;
int holder;


for(int j = 0; j < DLL_Size; j++)
{

        while(temp != NULL)
        {

                    if (temp->next != NULL && (temp->age < temp->next->age) )
                    {
                        holder = temp->age;

                        temp->age = temp->next->age;
                        temp->next->age = holder;
                    }
                    else
                            temp = temp->next;//increment node
            }
            temp = head;

}


}

这可行,但是当我尝试做类似的事情时:

node* holder;

...

holder = temp;
temp = temp->next;
temp->next = holder;

我的程序将编译并运行一个空白屏幕。任何指导将不胜感激。我猜交换我所有的变量会更容易(没有很多),但我想让我的代码更干净。谢谢。

【问题讨论】:

    标签: c++ linked-list doubly-linked-list


    【解决方案1】:

    这是因为你实际上并没有重新链接节点,所以你得到了一个无限循环。您需要更改 previous 节点的 next 链接以及 next-next 节点上的 prev 链接。


    如果你的列表是双向链接的,并且你有一个前一个指针和一个下一个指针,那么你可以这样做:

    node* next = temp->next;
    
    // Fix the links of the previous node, and the next-next node
    if (temp->prev)
        temp->prev->next = next;
    
    if (next->next)
        next->next->prev = temp;
    
    // Relink the two nodes that should be swapped
    temp->next = next->next;
    next->next = temp;
    
    next->prev = temp->prev;
    temp->prev = next;
    

    【讨论】:

    • 我猜我的初始链接丢失了指针。我正在尝试像你说的那样添加 prev->next & next->next->prev,但它仍然是空白的。我讨厌链表
    • 好的,我快到了,但由于某些原因,节点在重组期间丢失了。这是一张图片来显示正在发生的事情。 i.imgur.com/U3BGstr.png 感谢您的宝贵时间。我有指向第一个和最后一个节点的头和尾指针。 head->prev 和 tail-next 为 NULL
    猜你喜欢
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多