C,排序结构队列

时间:2012-07-01 10:32:17

标签: 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)。

1 个答案:

答案 0 :(得分: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;
}