2010-01-30 126 views
0

我正在嘗試使用基礎鏈接列表結構進行堆棧。鏈接列表實現問題

也許我錯了,但我遇到了remove()函數的問題。

int Stack::remove(){ 
    node* victim = new node; 
    int popped; 
    popped = top->element; 
    victim = top; 
    top = victim->next; 
    delete victim; 
    return popped; 
} 

我得到的glibc dectecting

雙重釋放或腐敗(出);

由於我正在爲受害者分配新的內存,我不必刪除受害者,還是我不必擔心的事情?

+0

沒有意義的是分配內存或使用新的受害者節點。記住一個指針只是一個參考,所以只要指向列表的頭部即可。保存數據值,將列表頭移動到下一個元素(可能要檢查NULL),然後刪除最初指向頭的臨時指針。這意味着你已經彈出了它。 – JonH 2010-01-30 02:47:24

回答

2

堆棧就像一堆正在清洗並相互疊放的盤子。這是第一個輸出(FILO數據類型)。也就是說,如果您的堆棧中讀2,7,8,然後它會顯示爲:

即首先將2被放置在堆棧,然後7,然後是8.如果你想刪除或彈出堆棧,你需要移動指針的頭部。你的代碼對我來說看起來有點奇怪...

int Stack::remove() 
{ 
    int datum;  //to store the popped value 
    node* temp=head; //assign pointer to head of list 
    datum = temp->data; //grab the data value stored at the head (or temp since they carry same reference) 
    head = temp->next; //move the head pointer (in our example now it points to 7) 
    delete temp; 
    return datum; 
} 
+0

您可能想要進行一些錯誤檢查以檢查是否存在空值。 – JonH 2010-01-30 02:46:18

+0

應該將temp-> next設置爲null,因爲有些人創建了自定義析構函數,所以如果一個節點被刪除,它會遞歸地刪除它指向的節點 – randomThought 2010-01-30 02:50:01

+0

@Jaelebi no在temp被刪除時,仔細查看temp的實現成爲名單的頭。頭被移動,然後使用刪除將temp解除分配。你可以說'temp-> next = NULL;'在'delete temp'之前;但是考慮到你正在刪除它並且函數結束它沒有任何用處。 – JonH 2010-01-30 02:52:53

1

沒有理由像victim那樣在remove()方法中分配堆內存。你想要的是:

int Stack::remove(){ 
    node* new_top = top->next; 
    int popped = top->element; 

    delete top; 
    top = new_top; 

    return popped; 
} 
1

你不需要爲victim分配節點。只需將堆棧頂部分配給它,如果它不是null,請將top設置爲其next指針,從victim檢索值,然後取消分配victim

它實際上並不是一個腐敗,而是一個內存泄漏 - 您正在分配一個節點,然後用victim = top;覆蓋該指針,從而失去剛剛分配的內存。