我的目录结构是这样的:如何删除双向链表中的第一个节点?
struct Node {
Node *next;
Node *prev;
T datum;
};
Node *first; // points to first Node in list, or 0 if list is empty
Node *last; // points to last Node in list, or 0 if list is empty
我试图做到以下几点:
void pop_front()
{
//copied from lecture slides
assert(!empty());
Node *victim = first;
first = first->next;
if(first != 0)
{
first->prev = 0;
}
delete victim;
victim=0;
}
的问题是,它给了我一个内存泄漏,当我做删除受害线。我不知道什么是错的。
编辑:这是怎么了添加节点:
//MODIFIES: this
//EFFECTS: inserts i into the front of the list
void pushit_tofront(const T &datum)
{
//if list is empty, update both the first and last element
//copied from lecture slides
Node *p = new Node;
p->datum = datum;
p->next = first;
if(empty())
{
first = last = p;
}
else
{
first = p;
}
}
你怎么知道它给你一个内存泄漏? –
这就是它的意思:“错误的对象0x100102c80:被释放的指针没有被分配 ***在malloc_error_break中设置一个断点来调试 ” – pigthatatepens
Off topic:推荐用'nullptr'和'victim'代替那些'0' = 0;'没多大用处。它即将超出范围。 – user4581301