【发布时间】:2020-06-04 18:29:27
【问题描述】:
我明天有一个面向对象的考试,但我仍然坚持使用链表。出于某种原因,我不太了解它们是如何工作的或如何正确实施它们。我看过很多视频和教程,但它仍然很复杂。我总是收到一个错误,它不会在控制台上打印任何内容,只是一个空白的黑页。有人可以告诉他们我做错了什么吗? 谢谢。
#include <iostream>
#include <string>
using namespace std;
struct node
{
string name;
int number;
node* next;
};
struct node* head = 0;
class Employees
{
private:
node* head, * tail;
public:
Employees()
{
head = NULL;
tail = NULL;
}
void addToList(string Name, int Num)
{
node* n = new node;
n->name = Name;
n->number = Num;
n->next = NULL;
if (head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
}
}
void PrintAll()
{
while (head != NULL)
{
node* current;
while (current != NULL)
{
cout << current->name << "\t";
cout << current->number;
}
}
}
};
int main()
{
Employees a;
a.addToList("Robert", 54);
a.addToList("Manny", 77);
a.PrintAll();
}
【问题讨论】:
-
有人能告诉他们我做错了什么吗? 没有使用你的调试器来弄清楚你的代码是如何无法按预期工作的。
-
您的
PrintAll()有错误。你有node* current;然后while (current != NULL)节点当前在哪里得到一个值? -
while (current != NULL)当你达到这个条件时,current的值是多少?同样在循环内你不要修改current,即一旦进入你就永远不会离开循环。 -
顺便说一句,“一旦进入你就永远不会离开循环”严格来说是错误的。您的代码具有未定义的行为,这就是所有可以肯定的说法
标签: c++ class linked-list singly-linked-list definition