首页 > 解决方案 > 如何从两个不同的双向链表中更改两个不同的节点?

问题描述

我在节点中有2个双向链表,我比较节点的数据,如果第二个列表的节点的数据大于第一个列表的节点的数据,我将切换节点。我怎样才能做到这一点。

这将删除旧节点并添加给定的节点。

void DoubleLinkedList::SwitchNodesFromList(Node* changeNode, int index)
{
RemoveAt(index);
if (index < 0 || index > size)
    throw "Error";
if (index == 0)
{
    head = changeNode;
    if (head->next != NULL)
        head->next->prev = head;
}
else
{
    Node* prv = findPreviousByPosition(index);
    prv->next = changeNode;
    if (prv->next->next != NULL)
        prv->next->next->prev = prv->next;
 }
}

保持节点这些会改变

 void ListController::SwitchNodes(Node* firstNodeOfList, Node* secondNodeOfList, int index)
{
Node* first = firstNodeOfList;
Node* second = secondNodeOfList;

Node* temp = first;

first->next = second->next;
first->prev = second->prev;
second->next = temp->next;
second->prev = temp->prev;
firstList->SwitchNodesFromList(second, index);
secondList->SwitchNodesFromList(first, index);
delete temp;
}

我比较项目,但我不能切换节点

void ListController::CompareItemsOfNodes()
{

for (int i = 0; i < firstList->Count(); i++)
{
    if (firstList->ElementAt(i) > secondList->ElementAt(i))
    {
        ReverseList(firstList);
        
    }
    else if (firstList->ElementAt(i) == secondList->ElementAt(i))
    {
        ReverseList(secondList);
       
    }
    else if (firstList->ElementAt(i) < secondList->ElementAt(i))
    {
        SwitchNodes(firstList->GetNode(i), secondList->GetNode(i), i);
       
    }
}
}

一定是这样的

标签: c++algorithmdata-structuresnodesdoubly-linked-list

解决方案


推荐阅读