我试图实现一个链表来解决算法问题 它基本上起作用,然而,事实证明我使用了太多的记忆 如果有人指出了以下析构函数设计的缺陷,我将不胜感激。
template<typename T>
struct Node {
Node(): item(0),next(0) {}
Node(T x): item(x),next(0) {}
T item;
Node* next;
};
template <typename T>
struct List {
List() : head(0),tail(0) {}
Node<T>* head;
Node<T>* tail;
void insert(T x) {
Node<T>* newNode = new Node<T>(x);
if(head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = tail->next;
}
}
void clearRecur(Node<T>* h) {
if(h) {
clearRecur(h->next);
delete h;
}
}
void clear() {
if(head) {
clearRecur(head);
}
}
};
答案 0 :(得分:0)
可以递归或迭代清除列表。
除了(恕我直言)正确版本之外,我使用了一种略微不同的方法 - 让private void playSong(String path) throws IllegalArgumentException, IllegalStateException, IOException {
startTime=0;
finalTime=0;
oneTimeOnly=0;
// changing the state of mediaPlayer inside its own callback is a bad practice.
//mediaPlayer.stop();
mediaPlayer.release(); // <<------ Add this before reference is gone.
mediaPlayer=null;
mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
}
本身&#34;负责任&#34;删除它的尾巴。这也会导致递归清除(但代码更少)。
递归清算:
Node
这就是我在当前项目中做到的方式。乍一看,它似乎很简单,工作得很好。当我们的beta测试人员开始玩时,我改变了主意。在现实世界的项目中,列表很长,以至于递归清除耗尽了堆栈内存。 (Yepp - 一个堆栈溢出。)我应该知道的更好!
因此,我迭代地进行了清算 - 其中&#34;责任&#34;已从template<typename T>
struct Node {
Node(): item(), next(nullptr) {}
Node(T x): item(x), next(nullptr) {}
~Node() { delete next; } // <== recursive clearing
T item;
Node* next;
// Using the default copy ctor would corrupt the memory management.
// Deleting it lets the compiler check for accidental usage.
Node(const Node&) = delete;
// Deleting assignment operator as well.
Node& operator=(const Node&) = delete;
};
template <typename T>
struct List {
List() : head(nullptr), tail(nullptr) {}
~List() { clear(); }
Node<T>* head, tail;
void insert(T x) {
Node<T>* newNode = new Node<T>(x);
if (head == nullptr) head = tail = newNode;
else {
tail->next = newNode;
tail = tail->next;
}
}
void clear() {
delete head;
head = tail = nullptr;
}
// Using the default copy ctor would corrupt the memory management.
// Deleting it lets the compiler check for accidental usage.
List(const List&) = delete;
// Delete assignment operator as well.
List& operator=(const List&) = delete;
};
移回Node
。 (API用户不会在发生这种情况时注意到这一点&#34;引擎盖下#34;。)
迭代清算:
List