我使用的是双向链表,我尝试使用通过引用传递给插入节点的数据说数据之前。我用string* data = new string(s);
但是分配内存,当我尝试使用数据我得到一个错误。
#ifndef __DOUBLYLINKEDLIST_H__
#define __DOUBLYLINKEDLIST_H__
//
//
#include
#include
using namespace std;
class DoublyLinkedList {
public:
DoublyLinkedList();
~DoublyLinkedList();
void append (const string& s);
void insertBefore (const string& s);
void insertAfter (const string& s);
void remove (const string& s);
bool empty();
void begin();
void end();
bool next();
bool prev();
bool find(const string& s);
const std::string& getData() const;
private:
class Node
{
public:
Node();
Node(const string& data);
~Node();
Node* next;
Node* prev;
string* data;
};
Node* head;
Node* tail;
Node* current;
};
void DoublyLinkedList::insertBefore(const string& s)
{
Node* ptr = head;
string* data = new string(s);
if (head == NULL)
{
append(s);
return;
}
if (head == current)
{
//this is where I get an error...
this->data= new Node();
current->prev = head;
current = head;
return;
}
没有理由使用指针string
,这迫使你来管理内存。使用简单string
代替。
但是,这这里是没有问题的。这里的局部变量具有比Node
的类成员相同的名称,并在节点成员被永远initalized。 Furtherthermore的DoublyLinkedList
具有本身没有这样的会员,所以this->data
是未知的。看到我的评论在这里:
void DoublyLinkedList::insertBefore(const string& s)
{
...
string* data = new string(s); // --> ok, but this is local variable
if (head == NULL)
{
append(s);
return; // ouch !!! memory leak !! data pointer is never freed
}
if (head == current)
{
//this is where I get an error...
this->data= new Node(); // --> 'this' is a DoublyLinkedList, not a Node
...
return;
}
现在,这虽这么说,是不是possbile先进行DoublyLinkedList
和它所包含的节点之间的混乱呢?看到这里纠正一个开始,但你需要做更多的处理节点之间的连接:
void DoublyLinkedList::insertBefore(const string& s)
{
Node* ptr = head;
if (head == NULL)
{
append(s);
return;
}
if (head == current)
{
string* data = new string(s);
Node nd = new Node();
nd->data = data; // initialize node's pointer
nd->prev = ... // you need to link new node to the rest
nd->next = ...
... // and you need to update the previous and next node
return;
}
现在,摆在首位说,一个字符串替换指针字符串。至少,你会避免泄漏内存,浅拷贝,和许多其它问题。然后你就可以专注于一个链表数据结构的实际问题更好。