c++ - 链表中的节点最后没有删除

标签 c++ list

我的功能是假设删除我的 Linked_list 中的最后一个节点,每个节点都有一个项目编号和一个年龄。但是当我调用我的函数并显示我的 Linked_list 时,该函数仅将项目编号设置为零,并且假设删除时年龄保持不变。

void deleteLastNode(Record  * & head){
Record *temp=head;

while(temp->next!=NULL){

    temp=temp->next;
}
    delete temp;


return;

};

//my output                                    item number  item age
//before the calling the function: 1st node    5000         1
//                                2nd node     6753         8 

//after calling the delete function: 1st node  5000         1
//                                   2nd node     0         8


//desired output                               
//before the calling the function: 1st node    5000         1
//                                 2nd node    6753         8 

//after calling the delete function: 1st node  5000         1

最佳答案

我认为您应该沿着列表向下走,直到到达倒数第二个 节点,然后将该节点指向NULL 并删除最后一个节点。我还认为更改您的函数以返回对列表新头部的引用是有意义的。

Record* deleteLastNode(Record* & head) {
    Record* temp = head;

    // for an empty list, just return NULL
    if (head == NULL) return NULL;

    // for a list one just one element, delete the head, and return NULL
    if (temp->next == NULL) {
        delete temp;
        head = NULL;
        return head;
    }

    // otherwise walk down the list until reaching the second to last element
    while (temp->next->next != NULL) {
        temp = temp->next;
    }

    delete temp->next;
    temp->next = NULL;

    // return the head of list with its final node removed
    return head;
}

关于c++ - 链表中的节点最后没有删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48435634/

相关文章:

c++ - 如何提取字符串中的特定值

c++ - 如何创建在构造函数期间初始化的类成员对象

java - 查找 ArrayList 中点的邻居

从 R 列表中删除特定类的元素

java - 将 ObservableList 中的修改合并到原始集合

html - 根据列表值设置无序列表的样式

c++ - C++ 编译器如何扩展前缀和后缀运算符++()?

c++ delete [] 总是挂起

c++ - 独特的结构列表

c++ - 在 C++ 中格式化整数