Tót*_*ila 2 c++ printing function linked-list
我目前正在学习 C++ 中的链表,我无法编写打印列表元素的打印函数;我的意思是我写了这个函数,但它不能正常工作。
#include <iostream>
using namespace std;
struct node
{
char name[20];
node* next;
};
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
int main()
{
node* head = NULL;
node* temp = head;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for (unsigned short i = 1; i <= people; i++)
{
addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
while (temp != NULL)
{
printList(temp);
temp = temp->next;
}
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
我想知道我做错了什么,请帮助我!
很明显,函数 addNewPerson 是错误的。
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
Run Code Online (Sandbox Code Playgroud)
您分配了新的节点人员。
node* person = new node;
Run Code Online (Sandbox Code Playgroud)
将其字段设置为 NULL
person->next = NULL;
Run Code Online (Sandbox Code Playgroud)
然后,如果 head 不等于 NULL,则将 person 设置为 person->next
person = person->next;
Run Code Online (Sandbox Code Playgroud)
由于 person->next 被设置为 NULL,这意味着现在 person 也将等于 NULL。
此外,该函数返回可以在函数中更改的 head。但是你忽略了 main 中的返回值
addNewPerson(head);
Run Code Online (Sandbox Code Playgroud)
至少应该有
head = addNewPerson(head);
Run Code Online (Sandbox Code Playgroud)
有效函数 addNewPerson 可能如下所示
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = head;
head = person;
return head;
}
Run Code Online (Sandbox Code Playgroud)
主要你必须写
for (unsigned short i = 1; i <= people; i++)
{
head = addNewPerson(head);
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
函数 printList 不输出整个列表。它只输出首个节点的数据成员名称。
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
Run Code Online (Sandbox Code Playgroud)
它应该如下所示
void printList(node* head)
{
for ( ; head; head = head->next )
{
cout << head->name << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
最后主要应该看起来像
int main()
{
node* head = NULL;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for ( unsigned short i = 0; i < people; i++ )
{
head = addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
printList( head );
cin.get();
}
Run Code Online (Sandbox Code Playgroud)