【问题标题】:How to swap the first and last elements of a linked list如何交换链表的第一个和最后一个元素
【发布时间】: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


【解决方案1】:

你的逻辑在第三点有缺陷。

  • 将最后一个节点设置在第一个节点旁边

应该是的。

  • 将旧的最后一个节点设置为新的第一个节点。

让我们来看看你的伪代码。我假设 first 是一个指向列表第一个节点的全局指针。

|200|50|300|25|
 ^
first

while 运行后 current 指针现在指向值为 300 的节点

|200|50|300|25|
 ^      ^
 first  current 

然后我们将值为 25 的节点更改为指向 first 从而导致此

|50|300|25|200|
    ^      ^
   current first 

之后,我们通过将列表指向 null 来关闭列表 first,并将 first 设置为 current

的下一个
|50|300|200|
    ^   ^
current first 

现在可以看到错误,对 25 的引用现在丢失了。 之后,我们将全局 first 指针更改为指向 current 的下一个节点,该节点应该是值为 25 的节点,但不是,因为它已被原始 替换>第一个节点。

要解决这个问题,您应该像这样更改函数的结尾。

Node * oldLast = current->getNext();
//set second to last to first node
current->setNext(first);
// set the first equal to the last node
first = oldLast;

【讨论】:

  • @JaMiT 根据您的输入调整了答案。
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多