class Node{
public:
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
~Node(){
delete next;
}
};
class List{
public:
Node* head;
Node* tail;
List(){
head = NULL;
tail = NULL;
}
~List(){
delete head;
}
void push_back(int data){
Node* n = new Node(data);
if(head == NULL){
head = tail = n;
}else{
tail->next = n;
tail = n;
}
}
void print(){
Node* temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
}
void deleteNode(int d){
Node* curr = head;
Node* prev = NULL;
while(curr != NULL){
if(curr->data == d){
if(prev == NULL){
head = head->next;
delete curr;
break;
}else{
prev->next = curr->next;
curr->next = NULL;
delete curr;
break;
}
}
prev = curr;
curr = curr->next;
}
}
};
int main(){
List l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.deleteNode(1);
l.print();
}
如果我從 1->2->3->4->5 中洗掉 1
預期輸出:2->3->4->5
輸出:free():在 tcache 2 中檢測到雙重空閑;
原因:節點類中的解構式。如果我洗掉它作業正常。
懷疑:如果我在 Node 類中洗掉 Node 類中的解構式,那么我該如何釋放記憶體。任何人都可以解釋解構式在 Node 和 List 類中是如何作業的。
有人可以幫我解決這個問題,或者可以提供替代解決方案。
謝謝!!!
uj5u.com熱心網友回復:
~Node(){ delete next; }使得很難從該串列中洗掉單個節點。它也會洗掉之后的所有節點。
我建議個人Nodes不要delete跟隨Nodes:
class Node {
public:
int data;
Node* next;
Node(int d) : // colon starts the member initializer list
data(d), next(nullptr)
{
// the body of the constructor can now be empty
}
// No user-defined destructor needed here
};
相反,解構式中的delete所有s :NodeList
~List() {
for(Node* next; head; head = next) {
next = head->next;
delete head;
}
}
與手頭的問題無關。這些只是建議:
您可以使建構式Node更加通用,因此可以Node在構造中提供下一個:
class Node {
public:
int data;
Node* next;
// `nullptr` below is a default argument that will be used if the
// user of this class does not provide a second argument
Node(int d, Node* n = nullptr) :
data(d), next(n)
{}
};
這可以在List名為的成員函式中使用push_front:
void push_front(int data) {
head = new Node(data, head);
if(!tail) tail = head;
}
與此無關,您甚至可以push_back在不改變當前的情況下更清楚一點Node:
void push_back(int data) {
Node* n = new Node(data);
if(tail) tail->next = n;
else head = n;
tail = n;
}
uj5u.com熱心網友回復:
跟進我的評論:扔掉你Node和List班級,并實際使用該語言:
#include <forward_list>
#include <iostream>
int main(){
std::forward_list< int > l { 1, 2, 3, 4, 5 };
l.remove( 1 );
for ( auto & node : l )
{
std::cout << node << " ";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441492.html
下一篇:如何將模板結構作為引數傳遞C
