2012-07-01 97 views
0

我可以使用一点帮助。我试图按年排序一排结构。C,排序结构队列

这是我的结构:

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; 
} 

} 

它,当我copmare打破:if((head->year)>(heads->year))。 我很确定我的问题是由于对head旁边的结构的不当引用(我将其命名为heads)引起的。

+1

“It break” - 请更具描述性。 –

+0

如果我理解正确,你的意图是*冒泡排序*链接列表? – wildplasser

+0

是的,我试图使用冒泡排序。 – ozech

回答

1

我省略了所有不重要的东西,并将链表bubble排序为这个skeletton。

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; 
} 
+0

非常感谢!我真的很感激它,它帮助了很多! ;) – ozech