0

基礎となるリンクされたリスト構造を使用してスタックを作成しようとしています。

間違っているかもしれませんが、remove() 関数に問題があります。

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

glibc を検出しています

二重解放または破損 (アウト)。

私は犠牲者に新しいメモリを割り当てているので、犠牲者を削除する必要はありませんか、それとも心配する必要はありませんか?

4

3 に答える 3

2

積み重なった皿は、洗って重ねる食器の束のようなものです。つまり、最初に入力され、最後に出力されます (FILO データ型)。つまり、スタックが 2、7、8 を読み取った場合、次のように表示されます。

8

7

2

つまり、最初に 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;
 }
于 2010-01-30T02:43:47.033 に答える
1

remove()で行っているように、メソッドにヒープ メモリを割り当てる理由はありませんvictim。あなたが望むものは:

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

  delete top;  
  top = new_top;

  return popped;  
}
于 2010-01-30T02:37:31.353 に答える
1

You don't need to allocate a node for victim. Just assign the top of the stack to it and, if it's not null, set top to its next pointer, retrieve the value from victim, and then deallocate the victim.

これは実際には破損ではなく、メモリ リークです。ノードを割り当ててから、そのポインタをオーバーライドして、victim = top;割り当てられたばかりのメモリを追跡できなくなります。

于 2010-01-30T02:41:09.457 に答える