链接列表并按字母顺序插入字符串
Linked List and inserting a string in alphabetical order
我正在编写一个程序,允许用户插入,删除,搜索和打印书籍。这些书必须按字母顺序打印出来。当我插入书籍时,它可以正常工作,但并不会使它们处于正确的顺序,并且会崩溃。这是我的插入功能的代码。
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
相关文章:
- 如何按数字顺序插入链表节点?
- 二叉树级别顺序插入 c++
- 按相反顺序插入矢量
- C++ 双向链表 - 插入同时保持递增顺序
- 在插入顺序已知时填充 Eigen3 稀疏矩阵的策略
- 如何修改函数以按C++的排序顺序插入每个项目
- 链接列表并按字母顺序插入字符串
- 按排序顺序将节点插入链表
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 在std ::或std :: unordered_set上保存插入顺序
- Unordered_set如何确定C 中的插入顺序
- 视觉使按顺序逐个插入C++
- 通过索引快速搜索,并将插入顺序保持在C 中
- 在STD :: MultiSet中维护插入顺序
- 双链接列表按顺序插入
- 我可以让 std::list 按顺序插入新元素吗?或者必须使用std::sort
- 在链表中按顺序插入节点
- c++中顺序插入/读取/删除最快的数据结构是什么?
- 如何按排序顺序插入
- 按字母顺序插入向量