這個問題很簡單,但是它涉及的面很廣,所以很具有學習的意義。
#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("排序後的結果為:\n");
s = Sort(s);
Output(s);
struct Emplyee my = { 21, "John", 24 };
printf("插入後的結果為:\n");
s = Insert(s, &my);
Output(s);
printf("刪除後的結果為:\n");
s = Delete(s, "John");
Output(s);
getchar();
}
struct Emplyee * Create()
{
struct Emplyee * s;
struct Emplyee * p = NULL;
printf("輸入三個員工的名字:\n");
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\t姓名:%s\t年齡:%d\n", 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;
}