C++链表实现,遍历时进入无限循环.猜测建设者出了问题



我是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

此处:

static void insertNodeAtEnd(int data)
{
Node newNode(data);
if (head == NULL)
{
head = tail = &newNode;
return;
}
tail->next = &newNode;
tail = &newNode;
numberOfNodes++;
return;
}

CCD_ 1是一个函数局部变量。当函数返回时,其生存期结束。你存储的指针是悬空的。当您稍后取消引用它们时,您将调用未定义的行为。

要动态分配节点,以便它们持久存在,您可以执行

Node* newNode = new Node(data);

目前尚不清楚为什么LinkedList的所有成员都被声明为static。其效果基本上是,您只能有一个链表,因为第二个链表将共享所有成员。

我通过创建一个新节点而不是直接实例化一个节点来实现它。在您的版本中发生的情况是,创建的节点被销毁,而通过创建新的节点,它将保持有效,直到明确删除

#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();
}

最新更新