我用c++做了一个链表。我不知道当试图指向列表的下一个元素时,程序停止了。
我的节点类如下:
class Node {
friend class List;
private :
Node* next;
public:
int value;
Node()
{
value = 0;
next = nullptr;
}
Node(int data)
{
this->value = data;
this->next = nullptr;
}
};
My List类有next和delete方法。每当调用Node类中的next属性时。程序卡住了。对于List类,我设置如下:
class List {
private:
Node* head;
public:
List ()
{
head = 0; // create an empty list
}
~List ()
{
delete head; // clean up the list and all nodes
}
Node* first () const
{
return head;
}
Node* next(const Node* n) const{
return n->next;
}
void append(int i)
{
Node* newNode = new Node(i);
if (head == nullptr){
head = newNode;
}
else
{
Node *ptr = head;
// the loop sets ptr to last node of the linked list
while (ptr->next != nullptr){
ptr = ptr->next;
}
// ptr now points to the last node
// store temp address in the next of ptr
ptr->next = newNode;
}
}
void insert(Node* n, int i)
{
Node *ptr = head;
Node *newNode = new Node(i);
newNode->next = n;
if(n==head)
{
head = newNode;
}
else
{
while(ptr->next != n)
{
ptr = ptr->next;
}
ptr->next = newNode;
}
}
void erase( Node* n)
{
Node *ptr = head;
Node *before ;
if (n->next == nullptr)
{
free(n);
return ;
}
if(head == n)
{
head = n->next;
free(n);
return ;
}
else
{
while(ptr!= n)
{
before = ptr;
ptr = ptr->next ;
}
before->next = ptr;
free(ptr);
free(n);
return ;
}
}
void printLst()
{
while(head != nullptr)
{
std::cout<<head->value<<" ";
head = head->next;
}
}
};
,以获得程序的完整视图。我使main函数非常简单:
int main()
{
List list;
list.append(55);
list.append(50);
list.append(20);
list.append(30);
list.insert(list.first(), 22);
list.insert(list.first(), 87);
list.printLst();
list.erase(list.first());
list.printLst();
}
有什么建议吗?
in erase never assign value给'before'赋值
Node* before;
那么
before->next = ptr;
错误C4703可能未初始化的本地指针变量'之前'使用ConsoleApplication1 C:workConsoleApplication1ConsoleApplication1.cpp 124
也-更重要的是你的printLst函数设置头为null
void printLst()
{
while (head != nullptr)
{
std::cout << head->value << " ";
head = head->next; <<========
}
}
你的print函数不应该改变head
列表。首先,然后返回null,所以这个
list.erase(list.first());
调用erase with null
抛出异常:读访问冲突。nnullptr。