链接列表
我是C++的初学者。我试图按队列顺序(FIFO)写一个动态分配的链表。该程序可以编译并运行。但我无法打印任何东西。所以我不知道链接或打印输出逻辑中是否存在问题。请帮忙。链接列表
#include <iostream> using std::cout;
using std::cin;
using std::endl;
using std::ios;
#include <iomanip>
using std::setw;
using std::left;
struct course
{
char coursename[32];
char term[32];
int unit;
char grade;
course* next;
};
void coutcourse(course*);
int main()
{
char input;
course *p;
course *prev;
course PHILO225 = {"PHILO-225", "SP2017", 3, 'A'}; // examples
course COMSC110 = {"COMSC-110", "SP2017", 4, 'A'}; //
course COMSC165 = {"COMSC-165", "FA2017", 4, 'X'};
course* start = 0;
course *t;
cout.setf(ios::left, ios::adjustfield);
while(true)
{
cout <<"Do you want to add a new course? [Y for yes, N for no]" << endl;
cin >> input;
if(input=='y'||input=='Y')
{
t= new course;
cout <<"Enter the name, term, units and grade for the new course in the same line, space separated." << endl;
cin >> t->coursename;
cin >> t->term;
cin >> t->unit;
cin >> t->grade;
for(p=start; p ; p=p->next)
{
t->next = 0;
if(start==0)
{
start=t;
p=t;
}
else
{
p->next=t;
p=t;
}
}
cout << endl <<setw(16)<<"COURSE"<<setw(16)<<"TERM" <<setw(16) <<"UNITS"<< setw(10)<<"GRADE" <<endl;
cout << "------------- -------- --------- -----------\n";
for (p=start;p;p=p->next)
coutcourse(p);
cout << endl;
continue;
}
if(input=='N'||input=='n')
break;
else
{
cout << "Invalid. Please try again." << endl;
continue;
}
}
for(p=start, prev=0; p ; prev=p, p=p->next)
{
if(p)
prev->next=p->next;
else
start=p->next;
delete p; // this can be written in another way. delete from start
}
}
void coutcourse(course* start)
{
cout<< setw(16) << start->coursename<< setw(16) << start->term << setw(16) << start->unit << setw(16) << start->grade << endl;
}
请告诉我错误在哪里。谢谢。
回答:
这显然是一个家庭作业问题(如果不是,请使用std::list
),因此我不打算给出完整答案。
for(p=start; p ; p=p->next)
如果p
的计算结果为false,则退出。 p
将在p
为NULL并且已达到列表的末尾时计算为false。
鉴于上述情况,如果列表为空,会发生什么情况?
以上是 链接列表 的全部内容, 来源链接: utcz.com/qa/258229.html