【问题标题】:How to sort using 'key': C如何使用“键”进行排序:C
【发布时间】:2015-07-12 02:15:03
【问题描述】:

我正在学习 C。我创建了一个程序来计算文本文件中单词的频率。 我的结构包含三个键(频率、单词、nextLink)。

问题是我已经使用键对结构数组进行了排序,但不知道如何处理这个。任何指导,链接都会很棒。

我正在提供我的 arrayOfStructs 排序代码

void sortArray(int array[], int count)
{
    int i,j,temp;
    for (i = 0; i < count; ++i)
    {
        for (j = i + 1; j < count; ++j)
        {
            if (array[i] > array[j])
            {
                temp =  array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
}

这是否是对 LinkedList 进行排序的可能方式

void sortList(struct Node *head)
{
    struct Node *i, *j, *temp;

    for (i = head; i != NULL ; i->next)
    {
        for (j = head->next; j != NULL; j->next)
        {
            if (head->frequency < head->next->frequency)
            {
                temp = head;
                head = head->next;
                head->next = temp;
            }
        }
    }
}

struct Node
{
    int frequency;
    char word[50];
    struct Node *next;
};

【问题讨论】:

    标签: c sorting linked-list key


    【解决方案1】:

    使用i = i-&gt;next 代替i-&gt;nextj = j-&gt;next 代替j-&gt;next

    void sortList(struct Node *head)
    {
        struct Node *i, *j, *temp;
    
        for (i = head; i != NULL ; i = i->next) // i = i->next
        {
            for (j = head->next; j != NULL; j = j->next) // j = j->next
            {
                if (head->frequency < head->next->frequency)
                {
                    temp = head;
                    head = head->next;
                    head->next = temp;
                }
            }
        }
    }
    

    【讨论】:

    • 差评的原因是什么? :O
    猜你喜欢
    • 2010-10-11
    • 2013-02-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2015-10-01
    • 1970-01-01
    相关资源
    最近更新 更多