我在使用生成的随机数填充链接列表时遇到问题,我的列表输出始终为空,我想用链接列表填充用户输入的n个元素。
我跟随其中一个教程,做了一切相同,但我想我可能会错过一些东西。非常感谢您的帮助。
struct Node
{
int number;
Node *next;
};
void FirstEl(Node *&first, Node *&last, int number)
{
Node *list = new Node;
list->number = number;
list->next = NULL;
first = list;
last = list;
};
bool isEmpty(Node *first)
{
if (first == NULL)
{
return true;
}
}
void Insert(Node *&first, Node *&last, int number)
{
if (isEmpty(first))
{
FirstEl(first, last, number);
}
else {
Node *list = new Node;
list->number = number;
list->next = NULL;
last->next = list;
last = list;
}
}
void ShowList(Node *current)
{
if (isEmpty(current))
{
cout << "List is empty\n";
}
else {
cout << "List: \n\n";
while (current != NULL)
{
cout << current->number << "\n";
current = current->next;
}
}
}
int main()
{
int menu = 0, n = 0, number;
Node *first = NULL;
Node *last = NULL;
cout << "Amount of element in List: ";
cin >> n;
srand(time(NULL));
for (int i = 0; i < n; i++)
{
number = (rand() % 10000 + 100);
Insert(first, last, number);
}
ShowList(first);
}
答案 0 :(得分:1)
如果条件不存在,您忘记将return false
添加到isEmpty
函数。