链接列表并按字母顺序插入字符串

Linked List and inserting a string in alphabetical order

本文关键字:顺序 插入 字符串 列表 链接      更新时间:2023-10-16

我正在编写一个程序,允许用户插入,删除,搜索和打印书籍。这些书必须按字母顺序打印出来。当我插入书籍时,它可以正常工作,但并不会使它们处于正确的顺序,并且会崩溃。这是我的插入功能的代码。

void BookList::Insert(Book* nBook)
    {
        string name;
        int quant;
        double p;
        cout << "Enter the title of the book." << endl;
        cin.ignore();
        getline(cin, name);
        cout << "Enter the number of quanities of this book." << endl;
        cin >> quant;
        cout << "Enter the price of this book." << endl;
        cin.ignore();
        cin >> p;
        nBook->title = name;
        nBook->quantity = quant;
        nBook->price = p;
        nBook->next = nullptr;
        //cout << "test" << endl;
        //If the current book is lexicographically smallest.
        if (first == nullptr) {
            first = nBook;
            cout << first->title << endl;
        }
        else if (nBook->title <= first->title)
        {
            cout << "new first" << endl;
            nBook->next = first;
            first = nBook;
        }
        else
        {
            cout << first->title << endl;
            //if current book is lexicographically small between two books.
            Book* prevPtr = first;
            while (prevPtr != nullptr)
            {
                cout << "Looking at: " << prevPtr->title << endl;
                if (prevPtr->title > nBook->title)
                {
                    break;
                }
                else
                {
                    prevPtr = prevPtr->next;
                }
            }
            nBook->next = prevPtr->next;
            prevPtr->next = nBook;
        }
    }

P.S。这在C 中谢谢

仅仅因为某些东西在编译时没有显示错误并不意味着它可以正常工作。为什么您使用没有参数的cin.ignore()?您要忽略的单个角色是什么?您意识到cin>>(某种或有一天)已经忽略了空格和返回字符,对

上下文需要更多的代码,但是似乎您正在尝试将新书的信息填充到一个" nbook"节点中,然后才能真正初始化新的" nbook"节点。

另外,我建议不要将该输出放在方法的末尾。如果您的方法是将新书添加到您的链接列表中,只需使用它添加它即可。将这些输出放入单独的方法或调用方法中。(或者,也许您只是为了调试目的而将其放入,在这种情况下为NVM)只是我的0.02