这个问题很简单,但是它涉及的面很广,所以很具有学习的意义。
#include<stdio.h> #include<string.h> #include<stdlib.h> struct Emplyee { int num; char name[20]; int age; struct Emplyee * next; }; void main() { struct Emplyee * Create(); void Output(struct Emplyee *); struct Emplyee * Sort(struct Emplyee *); struct Emplyee * Insert(struct Emplyee *, struct Emplyee *); struct Emplyee * Delete(struct Emplyee *, char name[20]); struct Emplyee * s = Create(); Output(s); printf("排序后的结果为: "); s = Sort(s); Output(s); struct Emplyee my = { 21, "John", 24 }; printf("插入后的结果为: "); s = Insert(s, &my); Output(s); printf("删除后的结果为: "); s = Delete(s, "John"); Output(s); getchar(); } struct Emplyee * Create() { struct Emplyee * s; struct Emplyee * p = NULL; printf("输入三个员工的名字: "); for (int i = 0; i < 3; i++) { s = (struct Emplyee *)malloc(sizeof(struct Emplyee)); s->num = i; gets(s->name); s->age = 21 + i; if (p == NULL) { s->next = NULL; p = s; } else { s->next = p; p = s; } } return p; } void Output(struct Emplyee * sl) { while (sl) { printf("工号:%d 姓名:%s 年龄:%d ", sl->num, sl->name, sl->age); sl = sl->next; } } struct Emplyee * Sort(struct Emplyee * s) { struct Emplyee temp, *last, *first, *p = s; for (int i = 0; i < 3; i++) { p = s; for (int j = 0; j<i; j++) { p = p->next; } first = p; struct Emplyee * min = p; while (p!= NULL) { if (p->age <min->age) { min = p; } p = p->next; } temp = *min; min->age = first->age; min->num = first->num;
strcpy(min->name,first->name); first->age = temp.age; first->num = temp.num;
strcpy(first->name,temp.name); } return s; } struct Emplyee * Insert(struct Emplyee * s, struct Emplyee * t) { struct Emplyee * p = NULL; struct Emplyee * q = s; while ((q->age < t->age) && q->next != NULL) { p = q; q = q->next; } if (t->age<=q->age)//说明不是在尾部插入 { if (s == q)//链表是空的 { p = t; p->next = NULL; } else { p->next = t; } t->next = q; } else//说明是在尾部进行插入 { q->next = t; t->next = NULL; } return s; } struct Emplyee * Delete(struct Emplyee * s, char name[20]) { struct Emplyee * p1 = NULL, *p2 = NULL; p1 = s; while ((strcmp(p1->name, name)) && p1->next != NULL) { p2 = p1; p1 = p1->next; } if (!(strcmp(p1->name, name))) { if (p1 == s) { s = p1->next; } else { p2->next = p1->next; } //free(p1);这个可能是编译器的问题,我只要使用,编译器就会提示我触动了断点,而事实上,我并未打任何断点。 } return s; }