我想在C中對鏈表進行排序,我的結構有字段「時間」,並且我想按時間升序排序。使用2個或更多節點對鏈表進行排序
但是我無法添加新的節點在2個或更多元素的情況下,0或1的代碼工作,例如,當我試試這個:7,6,2,9(這些是「時代」每個事件),我的代碼排序2,6,7,但在'9'時,我的終端停下來回答。
嗯,在此先感謝。問題的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// My struct
typedef struct event_t
{
double time;
char description[50];
int id_origin, id_dest;
struct event_t *prox;
} event_t;
bool event_sort (event_t **list, double time, char description[], int id_origin, int id_dest)
{
event_t *newelement = (event_t*)malloc(sizeof(event_t));
event_t *aux = *list;
if (newelement!=NULL) {
newelement->time = time;
strcpy (newelement->description, description);
newelement->id_origin = id_origin;
newelement->id_dest = id_dest;
// Here I check if the list is empty
if (*list==NULL) {
*list = newelement;
newelement->prox = NULL;
}
// Here I check if the list has one element
else if (aux->prox == NULL) {
if (aux->time <= time) {
aux->prox = newelement;
newelement->prox = NULL;
}
else {
*list = newelement;
newelement->prox = aux;
}
}
// case if the list have two or more nodes
else {
if (aux->time >= time) {
*list = newelement;
newelement->prox = aux;
}
else {
while ((aux->prox!=NULL)||(aux->prox->time<=time)) {
aux = aux->prox;
}
newelement->prox = aux->prox;
aux->prox = newelement;
}
}
return true;
}
else {
return false;
}
}
int main (int argc, char *argv[])
{
event_t *list = NULL, aux;
int number, i;
printf ("Enter the number of events: ");
scanf ("%d", &number);
printf ("\n");
for (i=0; i<number; i++)
{
printf ("Event %d\n", i+1);
printf ("Enter the time: ");
scanf ("%lf", &aux.time);
printf ("Enter the description: ");
scanf ("%s", aux.description);
printf ("Enter the id origin: ");
scanf ("%d", &aux.id_origin);
printf ("Enter the id dest: ");
scanf ("%d", &aux.id_dest);
printf ("\n");
event_sort (&list, aux.time, aux.description, aux.id_origin, aux.id_dest);
}
return 0;
}
如果您確實希望我們提供幫助,那麼顯示正確縮進的代碼將是一個很好的起點。 –
Sry,我不太擅長那個; x,我試着改進了一下。 – Kay
相關:['O(N log N)'(最好和最差) - 時間,'O(1)' - 用於單獨鏈接的線性列表的空間就地Mergesort算法](https://gist.github.com/zed/5651186#文件歸併-鏈表-PY)。它是['listsort.c'](http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html)的一般(較簡單)版本,它也支持雙向和循環鏈接列表。 – jfs