队列顺序中的链表

时间:2017-12-02 20:34:33

标签: c++ linked-list queue

我是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;
}

请告诉我哪里出错了。谢谢。

1 个答案:

答案 0 :(得分:0)

这显然是一个家庭作业问题(如果不是,请使用std::list),所以我不会给出完整的答案。

for(p=start; p ; p=p->next)

如果p评估为false,则退出。当p为NULL并且已到达列表末尾时,p将评估为false。

鉴于上述情况,如果列表为空,会发生什么?