0

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

这是我的结构:

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)。

4

1 回答 1

1

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

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;
}
于 2012-07-01T15:30:28.100 回答