-2

我对编程很陌生,一直在尝试按字母顺序插入标题,但我的插入功能似乎没有工作。请帮忙!

class Book {

public:
    Book() {
    }
    ;
    Book(char *newTitle) {
        strcpy(title, newTitle);
    }

    char *getBook() {
        return title;
    }

    int compareTo(Book *getbook) {
        return (strcmp(title, getbook->title));
    }

private:
    char title[81];

};

void BookList::insert(Book *newBook) {
    BookNode *node = new BookNode(newBook);
    BookNode *current = NULL;
    BookNode *previous = current;

    node->next = NULL;
    current = head;

    if (current == NULL) {
        head = node;
        head->next = NULL;
    }

    else {
        while (current->next != NULL && (newBook->compareTo(current->book) > 0)) {
            previous = current;

            current = current->next;
        }
        node->next = previous->next;
        previous->next = node;
    }
}
4

2 回答 2

1

我认为

while (current->next != NULL ...

应该读

while (current != NULL ...

目前看不出其他问题。

于 2013-03-15T18:20:26.587 回答
0

您并没有真正利用您的实现中的链接列表。插入链表应该是一个 O(1) 操作。非常简单高效。只需跟踪列表的末尾,您就可以删除 while 循环。

class BookList {
public:
    BookNode* head;
    BookNode* end;

    BookList():head(NULL), end(NULL) {}

    void insert(Book data) {
        if(head == NULL) {
            head = new BookNode(data);
            end = head;
        } else {
            end.next = new BookNode(data);
            end = end.next;
        }
    }
};
于 2013-03-15T19:15:00.267 回答