テストされていませんが、これはあなたが得ているアイデアの一部を表しているかもしれません. ただし、代わりに使用してみstd::list
ます:)コピー代入演算子と、適切に割り当て/割り当て解除するデストラクタを追加する必要があります。ここを参照してください。
template<typename T>
struct ListNode {
ListNode *next, *prev;
T value;
ListNode(const T &val): value(val), next(0), prev(0) {}
// copy constructor
ListNode(const ListNode &other): value(other.value) {
if(other.next)
append(new ListNode(*other.next));
}
void append(ListNode &n) {
next = &n; n.prev = this;
}
};
あなたがポインタである場合、ポインタメンバーが上記でコピーさvalue
れたのと同じ方法でそれをコピーしたいと思うでしょう:next
// copy constructor
ListNode(const ListNode &other): value(new T(*other.value)) {
if(other.next)
append(new ListNode(*other.next));
}
したがって、上記のリストの例では、次のようなことを試すことができます。
class LList {
LList(): first(0), last(0) {}
// copy constructor
LList(const LList &other):
first(0),
last(0)
{
if(other.first) {
first = new node(*other.first);
// find last item
last = first;
while(last->next) last = last->next;
}
}
~LList() {
if(first) delete first;
}
// TODO: copy assignment operator
private:
struct node {
node(int val): next(0), prev(0), o(new int(val)) {}
// copy constructor
node(const node &other): next(0), prev(0), o(*other.o)
{
if(other.next) {
next = new node(*other.next);
next->prev = this;
}
}
~node() {
delete o;
if(next) delete next;
}
// TODO: copy assignment operator
node *next;
node *prev;
int *o;
};
node *first; // The pointer to the first node (NULL if none)
node *last; // The pointer to the last node (NULL if none)
};
テストされていませんが、それがアイデアです...コンストラクターは、次のアイテムを操作することで再帰的に機能します。リンクで説明されているように、「TODO」項目は重要です。また、スマート ポインターを調べることもできます。スマート ポインターは、物を削除することを覚えておく必要がなくなり、例外の安全性が向上し、通常は生のポインターよりもはるかに安全なオプションです。