我正在尝试编写一个函数来删除链表的前元素,并将头指针设置为删除后的下一个元素。
这是我的代码:
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();
};
Andddddd .....这是问题所在,在 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)