0

项目清单

void MovieDatabase::  addActor(const string movieTitle, const string actorFirstName, const string actorLastName, const string actorRole ){
    bool found = false;
    Movie* temp;
    for(Movie* m= headMovie; m != NULL;  m = m-> next){
            if(m-> title == movieTitle){
                found = true;
                temp = m;
                break;
            }
    }

    if(found){
            if(headCast == NULL)
                    headCast =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
            else{
                    Cast *c =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
                    Cast *temp = headCast;
                    for(Cast* cur = headCast; cur -> next != NULL;  cur = cur -> next){
                             if(cur ->next -> lastName <  actorLastName){
                                    temp = temp -> next;
                            }
                            else{
                                    c -> next = cur -> next;
                                    temp  -> next= c;
                                    break;
                            }
                    }
            }
    }
    else
    cout << "The movie with a " << movieTitle << "  does not exist in the database,you can not add the actor. " << endl;
    size++;
}

大家好,我编辑了代码,现在我没有任何错误。但是,它没有显示任何输出。这意味着它不添加任何内容。在任何情况下,我都会发送用于显示的代码。

void MovieDatabase:: showActors(){
    for(Cast * cur= headCast;  cur != NULL; cur = cur -> next){
         cout  << cur  -> lastName << endl;
    }
}
4

1 回答 1

1

在这段代码中:

for(Cast* cur = headCast; cur != NULL;  cur = cur -> next){
    if(cur ->next -> lastName <  actorLastName){

您只检查那个cur != NULL,然后取消引用cur->nextcur->next可以为 NULL。

temp并且cur两者似乎都指向同一个节点。也许您打算将一个领先于另一个,以便您有一个指向前一个节点的指针以进行插入?

这是一个(未经测试的)实现:

    Cast *c =  new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
    Cast *prev = NULL; // maintain a pointer to the previous node. No previous node initially.
    Cast *cur;
    for(cur = headCast; cur != NULL;  cur = cur -> next)
    {
        if(cur -> lastName > actorLastName) break; // stop if we find a place to insert.
        prev = cur;                                // update previous pointer before looping.
    }
    if(prev != NULL)
    {
        prev -> next = c; // if there is a previous node, use 'c' as its next node.
    } else {
        headCast = c;     // otherwise 'c' is the new head node.
    }
    c -> next = cur;      // the 'current' node always goes after 'c'.
于 2012-12-22T15:20:05.113 回答