gpt4 book ai didi

C、对结构队列进行排序

转载 作者:行者123 更新时间:2023-11-30 15:56:24 25 4
gpt4 key购买 nike

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

这是我的结构:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com