我正在尝试对 C 中的链表进行排序,我的结构有字段“时间”,我想按时间升序排序。
但是我不能在末尾添加新节点以防 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;
}
最佳答案
部分问题是
while ((aux->prox!=NULL)||(aux->prox->time<=time))
我想你的意思是
while ((aux->prox!=NULL)&&(aux->prox->time<=time))
我没有寻找其他问题。
再见,
弗朗西斯
关于c - 对具有 2 个或更多节点的链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121088/