我的目錄結構是這樣的:如何刪除雙向鏈表中的第一個節點?
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