gpt4 book ai didi

c++ - 删除链表中的前面元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:06 26 4
gpt4 key购买 nike

我正在尝试编写一个函数来删除我的链表的前端元素并将头指针设置为删除的元素之后的下一个元素。

这是我的代码:

void LinkedList::delete_front(){
if(head != NULL){
if(head->next != NULL){
ListNode *tmp = head;
delete head;
head = tmp->next;
}
else {delete head; head = NULL;}
}
size--;
}

这是我的类定义:

class ListNode{

public:
Item data;
ListNode *next;
};
class LinkedList{

private:
ListNode *head;
int size;

public:
LinkedList();
~LinkedList();
bool empty();
void insert_front(Item i);
void insert_back(Item i);
void delete_front();
void delete_back();
void print();
};

Annddddd.....这就是问题所在,当在 valgrind 中运行时,这个错误会在第一次调用 delete_front() 之前弹出:

==4738== Invalid read of size 8
==4738== at 0x400B3C: LinkedList::delete_front() (in /home/jon/jball2_lab06/linkedlist)
==4738== by 0x400E59: main (in /home/jon/jball2_lab06/linkedlist)
==4738== Address 0x5a03f98 is 8 bytes inside a block of size 16 free'd
==4738== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4738== by 0x400B37: LinkedList::delete_front() (in /home/jon/jball2_lab06/linkedlist)
==4738== by 0x400E59: main (in /home/jon/jball2_lab06/linkedlist)

最佳答案

这里的问题:

if(head->next != NULL){
ListNode *tmp = head;
delete head;
head = tmp->next;
}

您将 temp 分配给 head,然后删除 head。然后尝试再次访问它。

关于c++ - 删除链表中的前面元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19326662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com