我正在尝试在C中对链接列表进行排序,我的struct有“time”字段,我希望按时间按升序排序。
但是我不能在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;
}
答案 0 :(得分:0)
部分问题是
while ((aux->prox!=NULL)||(aux->prox->time<=time))
我想你的意思是
while ((aux->prox!=NULL)&&(aux->prox->time<=time))
我没有寻找其他问题。
再见,
弗朗西斯
答案 1 :(得分:0)
我在这里看到一个错误:
else if (aux->prox == NULL)
{
if (aux->time <= time)
{
aux->prox = newelement;
newelement->prox = NULL;
}
else
{
*list = newelement;
newelement->prox = aux;
}
}
应该是
else if (aux->prox == NULL)
{
if (aux->time <= time)
{
aux->prox = newelement;
newelement->prox = NULL;
}
else
{
newelement->prox = aux;
*list = newelement;
}
}
否则在复制之前覆盖*list
指向的内容。