C、对结构队列进行排序

标签 c sorting queue structure

我需要一点帮助。我正在尝试按年份对结构队列进行排序。

这是我的结构:

struct element{

        int id;
        int sign;
        int year;
        int month;
        double amount;

        struct element *next;


    };

struct queue{
    struct element *head;
    struct element *tail;
    struct element *heads;
    struct element *temp;
    struct element *temph;

    int size;
};

这是我写的函数:

void sort(struct queue* queue){

if (queue->size == 0){
        printf("Struct is empty\n");}
else {

        struct element* head=queue->head;
        struct element* heads=queue->heads;
        struct element* temp=NULL;
        struct element* temph=queue->head;
        int i, size=queue->size;        

        for(i=0;i<size-1;i++){
        heads=head->next;
            if((head->year)>(heads->year)){

                temp=head;
                head=heads;
                heads=temp;         
            }


        head=head->next;
        heads=NULL;
        temp=NULL;
        }

head=temph;
}

}

当我执行以下操作时,它会中断:if((head->year)>(heads->year))。 我很确定我的问题是由于对 head 旁边的结构的不正确引用引起的(我将其命名为 heads)。

最佳答案

我省略了所有不重要的东西,并将链表冒泡排序简化为这个骨架。

void sort(struct queue* queue)
{
struct element **pp, *this;

    if (!queue->head ){
        fprintf(stderr, "OMG Struct is empty\n");
        return;
       }

        for(pp = &queue->head; this = *pp; pp = &(*pp)->next){
        struct element *other = this->next;
            if (!this->next) break;
            if (this->year < other->year) continue;
            /* 
            ** Now, Swap this (b) and other (c) 
            ** old situation: @a -> (b) -> (c) -> (d)
            ** new situation: @a -> (c) -> (b) -> (d) 
            */
            *pp = other;              /* @a  -> (c) */
            this->next = other->next; /* (b) -> (d) */
            other->next = this;       /* (c) -> (b) */
        }
/* Note: when we get here, "this" will contain the last non-NULL node in the
** chain, and can be used to reset the tail-pointer
*/
return;
}

关于C、对结构队列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11281240/

相关文章:

c - 为什么在 printf 中两次调用 inet_ntoa 会给出错误的输出?

c - 使用按键的 GLUT 旋转相机无法正常工作

sorting - D 编程语言中的就地基数排序

c++ - 谁可以帮助解释我的代码中有什么问题..在 C++ 中计算数组的种类

python - 按多列对 Pandas Dataframe 进行分组以获得特定值

c - 将链接器脚本文件链接到源代码

c - 输入字符而不是整数

c++ - 将项目添加到队列

algorithm - 队列平均 O(1) 入队和出队

c++ - 队列返回 pair.first 的错误值