我有一个函数,它的作用是组织一个词干单词的字典。我插入了一个函数调用,然后假设将其按正确的字母顺序放置。在列表的前面和中间添加可以,但在后面添加就不行了。我已经看了几个来源,但我不知道哪里出了问题。
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;
}
}
}发布于 2012-10-11 08:12:06
if (temp->next=NULL) {
prev->next = t;
}注意单个equal的用法。这样做的结果是将temp->next设置为NULL,然后评估始终为false的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;
}
}发布于 2012-10-11 08:19:50
if(temp->next=NULL)语句不会产生布尔值,而会产生赋值。这就是为什么列表末尾的插入看起来不起作用。
https://stackoverflow.com/questions/12830221
复制相似问题