【发布时间】:2016-05-14 14:26:56
【问题描述】:
有人告诉我,对链表进行排序的最佳方法是将该链表复制到一个数组中并对该数组进行排序。
#define SIZE 7000
所以我的链表:
typedef struct no{
char *nome;
int count;
struct no * prox;
}*link;
我的数组:
typedef struct MyArray
{
char name[141];
int count;
}MyArray;
MeuArray v[SIZE];
现在我的创建数组函数:
void create_array()
{
link tmp = head;
int cont = 0;
int i;
while (tmp != NULL)
{
strcpy(v[cont].nome, tmp->nome);
v[cont].count = tmp->count;
tmp = tmp->prox;
cont++;
}
for (i = 0; i < SIZE; i++)
printf("%s %d\n", v[i].nome, v[i].count);
}
不知道这是否正确。 现在我不知道哪个是最好的/最快的。 qsort 或其他。 如果是qsort:
int compare(struct MeuArray *elem1, struct MeuArray *elem2)
{
if ( elem1->count < elem2->count)
return -1;
else if (elem1->count > elem2->count)
return 1;
else
{
if (strcmp(elem1->name, elem2->name) > 1)
return 1;
else
return -1;
}
}
我也尝试过这种方式(排序我的链表):
void insertionSort(link current)
{
link head = current;
link inserP = head;
current = current->prox;
while (current != NULL)
{
inserP = head;
while (inserP != current)
{
if (inserP->count > current->count)
{
int temp = current->count;
current->count = inserP->count;
inserP->count = temp;
}
else /* if (inserP->count < current->count) */
inserP = inserP->prox;
/*else
{
if (strcmp(inserP->name, current->name) > 0)
{
char temp2 = strcpy(temp2, current->name);
strcpy(current->name, inserP->name);
strcpy(inserP->name, temp2);
}
else
inserP = inserP->prox;
} */
}
}
current = current->prox;
}
与:
link head = NULL;
感谢任何帮助。
编辑
我在 qsort 中我想先按数量比较,然后按名称比较。 问题是我只能按计数排序。 之后如何按名称排序?
代码:
int compare (const void * a, const void * b)
{
MeuArray *MeuArrayA = (MeuArray *)a;
MeuArray *MeuArrayB = (MeuArray *)b;
if ( MeuArrayB->count > MeuArrayA->count )
return 1;
else if ( MeuArrayB->count < MeuArrayA->count )
return -1;
else
{
if (strcmp(MeuArrayB->nome, MeuArrayA->nome))
return 1;
else
return -1;
}
}
【问题讨论】:
-
调试器......................
-
你的链接列表的内容是什么?为什么它有一个计数变量?
-
你的问题漏掉了一个问题 ;-) 你的问题是什么?代码是否产生错误或不正确的结果?您尝试过哪些输入值?
-
存储指向指针数组的指针。然后 qsort。
-
我的问题是。如果这是如何从链表创建数组以及如何实现 qsort。或者有更好/更快的方法。
标签: c arrays sorting linked-list