C ++:链接列表排序 [英] C++:Linked list ordering

查看:41
本文介绍了C ++:链接列表排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,应该组织一个词干词典.我插入了一个函数调用,然后假设将其按正确的字母顺序放置.将其添加到列表的前面和中间是可行的,但是不能添加到列表的后面.我查看了几个消息源,但我不知道出了什么问题.

I have a function and it is suppose to organize a dictionary of stemmed words. I have a function call inserted then suppose to place it in the right alphabetical order. Adding to the front and middle of the list works, but adding to the back doesn't. I've looked at several sources and I can't tell what's wrong.

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) {
    prev->next = t; 
}

请注意单个等号的用法.这样的效果是将 temp-> next 设置为 NULL ,然后计算 if(NULL)始终为假.您应该使用 == .

Note the usage of a single equal. The effect of this is to set the temp->next to NULL and then evaluate if (NULL) witch will be always false. You should use ==.

这可能会完成工作:(对不起,我现在没有编译器可以对其进行测试)

This will probably do the job: (sorry, I don't have a compiler right now to test it)

#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;
    }
}

这篇关于C ++:链接列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆