【问题标题】:C, Sorting a queue of structuresC、对结构队列进行排序
【发布时间】:2012-07-01 10:32:16
【问题描述】:

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

这是我的结构:

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-&gt;year)&gt;(heads-&gt;year))。 我很确定我的问题是由于对head 旁边的结构的引用不当引起的(我将其命名为heads)。

【问题讨论】:

  • “它坏了”——请描述得更清楚。
  • 如果我理解正确,您的意图是冒泡排序一个链表?
  • 是的,我正在尝试使用冒泡排序。
  • 比:尝试接受@david-schwartz 的建议:对链表进行排序意味着更改指向项目的指针。这可能是 ->next 指针或“外部”头指针,它指向第一项。
  • @wildplasser, @david-schwartz 我不确定我是否完全理解。排序应如下所示:temp-&gt;next=head-&gt;next;head-&gt;next=heads-&gt;next;heads-&gt;next=temp-&gt;next;?

标签: c sorting queue structure


【解决方案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;
}

【讨论】:

  • 非常感谢!我真的很感激,它帮助了很多! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多