我试图在C中对链接列表进行排序,我的结构有" time“字段,我想按时间按升序排序。
但是我不能在两个或更多元素的末尾添加新节点,例如,当我尝试这样做时: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;
}
发布于 2014-03-01 14:43:22
问题的一部分是
while ((aux->prox!=NULL)||(aux->prox->time<=time))
我想你是说
while ((aux->prox!=NULL)&&(aux->prox->time<=time))
我没有寻找其他的问题。
再见,
弗朗西斯
发布于 2014-03-01 14:48:52
我在这里看到一个错误:
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
所指向的内容。
https://stackoverflow.com/questions/22121088
复制相似问题