【问题标题】:C++ removing node from back --singly linked listC ++从后面删除节点--单链表
【发布时间】:2016-05-17 17:33:01
【问题描述】:

为什么我的代码不会删除链表的最后一个元素?我创建了一个当前指针来遍历我的列表并跳出循环..(下一个是我的结构中称为 Card_Node 的点)。应该很容易回答,只是不知道为什么它不会删除列表中的最后一个节点”

    Card_Node *current; 
    current = front;
    while ( current->next->next != NULL){
    {   
        current = current-> next;
    }   
    Card a = current->next->card;
    return a;
    delete current->next;
    current->next = NULL;
}

【问题讨论】:

  • 已更改但仍不会删除..... Card_Node *current;当前=前面;而(当前->下一个->下一个!= NULL){当前=当前->下一个; } 卡片 a = 当前 -> 下一个 -> 卡片;返回一个;删除当前->下一个;当前->下一个 = NULL; }
  • 你不使用std::list有什么原因吗?

标签: c++ linked-list


【解决方案1】:
return current->next->card;   // return !!
delete current->next;         // so this will never be executed
current->next = NULL;

更新

由于下面的评论要求进一步输入,这里是我试图保持原始原则的更新。

if (front == nullptr)  // Special handling of empty list
{
    // Nothing to return - add error handling - throw exception perhaps
    // or:
    return ???; // A default card perhaps
}
if (front->next == nullptr)  // Special handling of list with one element
{
    // Only one element
    Card a = front->card;
    delete front;
    front = nullptr;
    return a;
}

Card_Node *current; 
current = front;
while ( current->next->next != NULL)  // Iterate to find last element
{   
    current = current-> next;
}

// Now current->next is last element, i.e. the one to remove   
Card a = current->next->card;
delete current->next;
current->next = NULL;
return a;

【讨论】:

  • 我现在做了 Card a = current->next->card;返回一个;删除当前->下一个,但它仍然不会删除
【解决方案2】:

您正在以两种不同的方式检查 NULL;这应该只做一次。如果您考虑一下当列表中只有一个元素时您的代码会做什么(在调试器中或在纸上遍历它),那么您应该意识到问题所在。

【讨论】:

    【解决方案3】:

    你的代码有几个问题:

    1. 如果列表包含的节点少于两个,则您没有考虑在内。
    2. 您在delete 之前调用return,因此跳过了delete
    3. while 循环中的左大括号过多。
    4. 当列表中有两个或更多节点时,您没有将前一个节点的 next 指针设置为 NULL。
    5. 如果列表中只有一个节点,则不要将 front 设置为 NULL。

    试试这个:

    if (!front) {
        // no cards in the list, do something...
        return Card();
    }
    Card_Node *current = front;
    Card_Node *previous = NULL;
    while (current->next != NULL) {
        previous = current;
        current = current->next;
    }   
    Card a = current->card;
    delete current;
    if (previous != NULL) {
        previous->next = NULL;
    }
    if (front == current) {
        front = NULL;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 1970-01-01
      • 2017-10-21
      • 2013-08-30
      • 2019-05-10
      • 1970-01-01
      • 2020-02-04
      相关资源
      最近更新 更多