我如何排序中的一个字段结构的链接列表? [英] How do I sort a linked list of structures by one of the fields?
本文介绍了我如何排序中的一个字段结构的链接列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
哇现在我知道我不。哈哈。
Wow now i know I dont. Lol.
我有我的结构是这样的:
I've got my structure like this:
struct Medico{
int Id_Doctor;
int Estado;
char Nombre[60]; ////focus on this part of the structure, this is name.
char Clave_Acceso[20];
char Especialidad[40];
struct Medico *next;
};
和我想组织结构取决于名称(按字母顺序排列..)关于如何解决这个问题的任何想法?
And I want to organize the structure depending on the name(alphabetical order..) any ideas on how to tackle this problem?
例如:
Albert Haynesworth
Bob Marley
Carl Johnson
感谢您非常先进。 :)(C,UNIX)
Thank you very much in advanced. :)(C, Unix)
推荐答案
实施了在C链表一个合并是很容易的:
Implementing a mergesort over a linked list in C is quite easy:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
struct node *next;
char *data;
};
struct node *
divlist (struct node *n) {
int i = 0;
if (n) {
struct node *tail, *n2 = n;
while (1) {
n2 = n2->next;
if (!n2) break;
if (i++ & 1) n = n->next;
}
tail = n->next;
n->next = NULL;
return tail;
}
return NULL;
}
struct node *
mergelists(struct node *a, struct node *b) {
struct node *n;
struct node **last = &n;
if (!a) return b;
if (!b) return a;
while (1) {
if (strcmp(a->data, b->data) > 1) {
*last = b;
last = &b->next;
b = b->next;
if (!b) {
*last = a;
break;
}
}
else {
*last = a;
last = &a->next;
a = a->next;
if (!a) {
*last = b;
break;
}
}
}
return n;
}
struct node *
sortlist (struct node *n) {
struct node *tail = divlist(n);
if (!tail) return n;
return mergelists(sortlist(n), sortlist(tail));
}
int main(int argc, char *argv[]) {
int i;
struct node *n1, *n = NULL;
for (i = argc; --i >= 1;) {
n1 = (struct node *)malloc(sizeof(*n1));
n1->data = argv[i];
n1->next = n;
n = n1;
}
n1 = n = sortlist(n);
while (n1) {
printf("%s\n", n1->data);
n1 = n1->next;
}
return 0;
}
请注意,你将不得不修改此code使用你的数据结构和正确的比较!
Note that you will have to modify this code to use your data structure and the right comparison!
这篇关于我如何排序中的一个字段结构的链接列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文