链表和按字母顺序插入字符串

时间:2019-03-18 21:24:21

标签: c++ data-structures linked-list

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

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 ++中 谢谢

1 个答案:

答案 0 :(得分:0)

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

上下文需要更多代码,但似乎您是在尝试实际初始化新的“ nBook”节点之前,将新书的信息填充到“ nBook”节点中。

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