C++:链表排序
C++:Linked list ordering
我有一个函数,它应该组织一个词干词典。我插入了一个函数调用,然后假设将其按正确的字母顺序放置。添加到列表的前面和中间有效,但添加到后面则不行。我看了几个来源,我说不出出了什么问题。
void dictionary::insert(string s) {
stem* t = new stem;
t->stem = s;
t->count =0;
t->next = NULL;
if (isEmpty()) head = t;
else {
stem* temp = head;
stem* prev = NULL;
while (temp != NULL) {
if (prev == NULL && t->stem < temp ->stem) {
head = t;
head->next = temp;
}
prev = temp;
temp = temp->next;
if(t->stem > prev->stem && t->stem < temp->stem ){
prev->next =t;
t->next=temp;
}
}
if(temp == NULL && t->stem > prev->stem){
prev->next=t;
}
}
}
语句if(temp->next=NULL)不会导致布尔值,而是导致赋值。 这就是为什么插入列表末尾似乎不起作用的原因。
if (temp->next=NULL) {
prev->next = t;
}
请注意单个等号的用法。这样做的效果是将temp->next
设置为NULL
,然后评估if (NULL)
女巫将始终为假。您应该使用 ==
.
这可能会完成这项工作:(抱歉,我现在没有编译器来测试它)
#include <string>
struct node;
struct node
{
node* next;
std::string value;
};
node* head = NULL;
void insert(const std::string& word)
{
node* n = new node;
n->value = word;
node* temp = head;
node** tempp = &head;
while (true)
{
if (temp == NULL or temp->value > word)
{
n->next = temp;
*tempp = n;
return;
}
temp = temp->next;
tempp = &temp->next;
}
}
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 在排序链表中插入结构并将其写入二进制文件
- C++:按数字排序链表错误
- 家庭作业的排序链表程序中的分段错误
- 删除已排序链表中的值
- 排序链表-移动节点还是交换数据成员
- 单排序链表-无限循环
- 插入排序链表c++
- 冒泡排序链表C++
- 将元素添加到排序链表C++时出现问题
- 升序排序 - 链表
- 气泡排序链表不排序
- C++ 中的排序链表不会插入
- 删除具有重复相同值的已排序链表中的重复值
- 未排序链表实现检查完毕
- 插入排序链表c++
- c++中从排序链表中删除重复值节点的方法
- 排序链表和addSorted函数问题