【发布时间】:2021-06-08 23:47:11
【问题描述】:
我正在尝试交换链表的第一个和最后一个元素,但我无法找到解决方案。我的逻辑或伪代码是:
- 将倒数第二个节点的
next设置为第一个节点。 - 将第一个节点的
next设置为nullptr。 - 将最后一个节点的
next设置为第一个节点。
我当前的代码是:
void SingleList::swapFirstAndLast()
{
Node *current = first;
while (current->getNext()->getNext() != nullptr)
{
current = current->getNext();
}
// current is equal to the second to last node
//set last node to first node
current->getNext()->setNext(first);
//set first node to nullptr
first->setNext(nullptr);
//set second to last to first node
current->setNext(first);
// set the first equal to the last node
first = current->getNext();
}
而我目前的输出是:
Swap first and last nodes:
List before : 200 50 300 25
---------------------------
List after : 200
我不一定要寻找直接的代码答案,但是对于我在这里缺少的任何提示或建议将不胜感激。
【问题讨论】:
-
交换链表的元素不应该依赖于元素在链表中的位置。
-
只交换2个节点中的数据,而不是维护列表的指针。
-
当您执行
first->setNext(nullptr)时,您将失去对第一个元素之后所有内容的唯一引用。 -
@MarkRansom 这个问题不是关于效率,而是关于学习处理指针和在列表中移动指针。我知道如何交换微不足道的数据。
-
@MFisherKDX 您建议将新的最终节点设置为 null 的好方法是什么?
标签: c++ list linked-list