gpt4 book ai didi

c++ - 在C++中按字母顺序将节点添加到链表

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:02 26 4
gpt4 key购买 nike

我正在尝试创建一个链接列表,从用户那里获取单词,直到输入为空,然后添加每个单词,以便列表保持按字母顺序排列。但是,仅打印第一个节点。我做错了什么吗?这是我所拥有的(减去 header 和声明):

    //put in additional nodes until the input is blank
while(in != " "){
cin >> in;
newPtr->data = in;
prevPtr->data = "";
prevPtr->next = NULL;
nextPtr = list;
//shift the prevPtr and nextPtr until newPtr is alphabetically between them
while(!(prevPtr->data<=in && nextPtr->data>in)){
prevPtr = nextPtr;
nextPtr = prevPtr->next;
}
//make newPtr point to the next node
if(nextPtr != NULL){
newPtr->next = nextPtr;
}
//make newPtr the "next" pointer of the previous node, if any
if(prevPtr != NULL){
prevPtr->next = newPtr;
}
//if there's nothing before newPtr, make it the first node
else{
list = newPtr;
}
printList(list);
};

最佳答案

我会把它作为评论发布,因为我担心我可能会遗漏一些东西,但我还不能这样做,所以这里有一个非答案:

是什么阻止您使用 std::list ?你可以插入一个词,检查它是否非空,立即应用标准 sorting algorithm (它依赖于排序对象的比较运算符)并打印它。它速度很快,您的代码简短易读,而且您无需花时间重新发明轮子。

PS:如果你想测试一个空字符串,我认为它应该是 "",而不是 ""

关于c++ - 在C++中按字母顺序将节点添加到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com