我是C++的新手。我正在尝试实现一个链表。调用遍历函数时,输出进入无限循环(输出显示在底部)。当我在insertNodeAtEnd函数中使用'new‘而不是构造器时没有错误,但我读到在C++中这通常不是一个好的做法,最好习惯使用构造器。我做错了什么?
#include <iostream>
struct Node
{
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
~Node() {}
};
class LinkedList
{
public:
LinkedList()
{
std::cout << "Linked list created \n";
}
static Node *head;
static Node *tail;
static int numberOfNodes;
static int getNumberOfNodes()
{
return numberOfNodes;
}
static void insertNodeAtEnd(int data)
{
Node newNode(data);
if (head == NULL)
{
head = tail = &newNode;
return;
}
tail->next = &newNode;
tail = &newNode;
numberOfNodes++;
return;
}
static void traverse()
{
if (numberOfNodes == 0)
{
std::cout << "Linked list is empty \n";
}
Node *curr = head;
while (curr != NULL)
{
std::cout << curr->data << std::endl;
curr = curr->next;
}
return;
}
~LinkedList()
{
std::cout << "Linked list destroyed \n";
}
};
Node *LinkedList::head = NULL;
Node *LinkedList::tail = NULL;
int LinkedList::numberOfNodes = 0;
int main()
{
LinkedList linkedlist;
linkedlist.insertNodeAtEnd(40);
linkedlist.insertNodeAtEnd(50);
linkedlist.insertNodeAtEnd(60);
linkedlist.insertNodeAtEnd(70);
linkedlist.traverse();
}
这是输出。(无限循环,必须在控制台中终止。)
Linked list created
70
70
70
70
70
70
70
发布于 2021-05-06 18:12:03
这里:
static void insertNodeAtEnd(int data)
{
Node newNode(data);
if (head == NULL)
{
head = tail = &newNode;
return;
}
tail->next = &newNode;
tail = &newNode;
numberOfNodes++;
return;
}
newNode
是一个函数局部变量。当函数返回时,它的生命周期就结束了。你存储的指针是悬空的。当您稍后取消对它们的引用时,您将调用未定义的行为。
要动态分配节点,使其持久化,您可以这样做
Node* newNode = new Node(data);
目前还不清楚为什么LinkedList
的所有成员都被声明为static
。其效果基本上是您只能有一个链表,因为第二个链表将共享所有成员。
发布于 2021-05-06 18:15:55
我通过创建一个新的Node而不是直接实例化一个来让它工作。在您的版本中发生的情况是,创建的节点被销毁,而通过创建新的节点,它将保持有效,直到显式删除
#include <iostream>
struct Node
{
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
~Node() {}
};
class LinkedList
{
public:
LinkedList()
{
std::cout << "Linked list created \n";
}
static Node *head;
static Node *tail;
static int numberOfNodes;
static int getNumberOfNodes()
{
return numberOfNodes;
}
static void insertNodeAtEnd(int data)
{
Node* newNode = new Node(data);
if (head == NULL)
{
head = tail = newNode;
return;
}
tail->next = newNode;
tail = newNode;
numberOfNodes++;
return;
}
static void traverse()
{
if (numberOfNodes == 0)
{
std::cout << "Linked list is empty \n";
}
Node *curr = head;
while (curr != NULL)
{
std::cout << curr->data << std::endl;
curr = curr->next;
}
return;
}
~LinkedList()
{
std::cout << "Linked list destroyed \n";
}
};
Node *LinkedList::head = NULL;
Node *LinkedList::tail = NULL;
int LinkedList::numberOfNodes = 0;
int main()
{
LinkedList linkedlist;
linkedlist.insertNodeAtEnd(40);
linkedlist.insertNodeAtEnd(50);
linkedlist.insertNodeAtEnd(60);
linkedlist.insertNodeAtEnd(70);
linkedlist.traverse();
}
https://stackoverflow.com/questions/67423722
复制相似问题