【发布时间】:2019-10-17 21:17:32
【问题描述】:
我刚刚开始学习 C++。
我正在尝试创建一个不使用类的链表。所以,在主函数中,我有头尾指针。之后,我要求用户执行任务。如果他想添加一个新学生,用户必须输入 A。要打印列表,用户必须输入 P 并退出程序。我编写了以下程序来完成任务:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct Student {
string name;
Student* next;
};
void add_student(Student *, Student *);
void print_list(Student *);
int main()
{
Student *head, *tail;
head=NULL;
tail=NULL;
while (true) {
cout << "\nOptions:\n";
cout << "To add Student [A]\n";
cout << "To print Student list [P]\n";
cout << "Quit Q [Q]\n";
string choice = "";
cin >> choice;
if (choice.compare("A") == 0) {
add_student(head, tail);
cout << "Book successfully added.\n";
}
else if (choice.compare("P") == 0) {
print_list(head);
}
else if (choice.compare("Q") == 0) {
cout << "Bye!";
break;
}
else {
cout << "Invalid choice.\n";
}
}
}
void add_student(Student *head, Student *tail)
{
string name;
cout << "Enter name of student \n";
cin >> name;
Student *temp = new Student;
temp->name = name;
temp->next = NULL;
if(head==NULL)
{
head=temp;
tail=temp;
temp=NULL;
}
else
{
tail->next=temp;
tail=temp;
}
// Check student has been added successfully.
print_list(head);
}
void print_list(Student *head)
{
cout << "Student list is as following:\n";
Student *temp=new Student;
temp=head;
while(temp!=NULL)
{
cout<< temp->name <<"\n";
temp = temp->next;
}
}
但是,问题是每次添加新学生时,都会将其添加为列表中的第一个元素,而不是最后添加。我认为,我在通过引用传递时犯了一些错误。
请您检查并建议我在哪里做错了。这会很有帮助,因为我是 C++ 初学者,我真的很想从错误中吸取教训。
【问题讨论】:
-
head=tempinadd_student没有任何用处,因为 head 是一个局部变量,是传递的指针的副本 -
谢谢。我会从下次开始照顾。你能帮我找出我的错误吗?
-
@Jean-FrançoisFabre 哦,好吧。谢谢。我应该改变什么,以便它也改变主函数中的头部。
-
通过引用传递指针应该可以工作:
void add_student(Student *&head, Student *&tail) -
为什么
print_list分配了一个new Student然后立即失去指向它的指针?