链接列表从原始指针到智能指针的转换

时间:2015-11-14 16:31:33

标签: c++ pointers smart-pointers

如何实现从原始指针到智能指针的链表代码。任何指南都会有所帮助。这是我的code

实际上我对智能指针的类型更加困惑。共享或独特,将是什么头。我将如何在析构函数中删除整个列表?

#include <iostream>

class List{

private:

struct Node{
 int datum;
 Node* next;

 Node(int d, Node* n):datum(d),next(n){std::cout<<"Constructor: "<<datum<<"\n";}
 ~Node(){std::cout<<"Destructor: "<<datum<<"\n";}

};
Node* head=nullptr;

public:

~List() {
        while (head) {
            Node *temp = head->next;
            delete head;
            head = temp;
        }
    }

void append(int d){
    Node* t = getLastNode(head);
    (t ? t->next : head) = new Node(d, nullptr);

    }

  Node *getLastNode(Node *n) const {
        for (Node *it = n; it; it = it->next)
            if (!it->next)
                return it;
        return nullptr;
    }    


};


int main(){

List l1;
l1.append(1);
l1.append(2);    


}

0 个答案:

没有答案