首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++:Linked列表排序

C++:Linked列表排序
EN

Stack Overflow用户
提问于 2012-10-11 07:54:49
回答 2查看 192关注 0票数 0

我有一个函数,它的作用是组织一个词干单词的字典。我插入了一个函数调用,然后假设将其按正确的字母顺序放置。在列表的前面和中间添加可以,但在后面添加就不行了。我已经看了几个来源,但我不知道哪里出了问题。

代码语言:javascript
运行
复制
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;
        }
    }
}
EN

回答 2

Stack Overflow用户

发布于 2012-10-11 08:12:06

代码语言:javascript
运行
复制
if (temp->next=NULL) {
    prev->next = t; 
}

注意单个equal的用法。这样做的结果是将temp->next设置为NULL,然后评估始终为false的if (NULL)。您应该使用==

代码语言:javascript
运行
复制
#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;
    }
}
票数 1
EN

Stack Overflow用户

发布于 2012-10-11 08:19:50

if(temp->next=NULL)语句不会产生布尔值,而会产生赋值。这就是为什么列表末尾的插入看起来不起作用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12830221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档