大家好,我正在尝试在两个双向链表之间完全交换两个节点(值和地址也是如此)。只有处于相同位置的节点可以交换,即位置 2 的节点只能被另一个链表中位置 2 的节点交换。考虑以下 2 个 LinkedList 的示例:
815 102 162 524
622 101 830 754
假设我们要交换第三个元素,即 162 和 830。交换后,LinkedLists 变为:
815 102 830 524
622 101 162 754
我已经尝试了下面的代码,但它没有交换以前的元素。
void swapNodes(Node* firstListNode,Node* secondListNode)
{
Node* FirstNodeNext = firstListNode->next;
Node* FirstNodePrev = firstListNode->previous;
Node* SecondNodeNext = secondListNode->next;
Node* SecondNodePrev = secondListNode->previous;
//if the nodes are heads
if (firstListNode->previous == NULL && secondListNode->previous == NULL)
{
firstListNode->next = SecondNodeNext;
secondListNode->next = FirstNodeNext;
}
// if the nodes are tails
else if(firstListNode->next == NULL && secondListNode->next == NULL)
{
firstListNode->previous = SecondNodePrev;
secondListNode->previous = FirstNodePrev;
}
else
{
firstListNode->next = SecondNodeNext;
firstListNode->previous = SecondNodePrev;
secondListNode->next = FirstNodeNext;
secondListNode->previous = FirstNodePrev;
}
}
我怎样才能完成这个任务?
else if 不交换前面的元素,例如,如果我们将值 524 和 754 传递给函数,它应该是尾部并执行 else if 语句,因为它没有下一个节点。
交换后应该是:
815 102 162 754
622 101 830 524
代码不会交换之前的节点。