#include <stdio.h>
struct Person {
char * Name;
int Age;
struct Person * Next;
};
struct List {
char * Name;
struct Person * Next;
};
void InitList(struct List *pList, char *Name)
{
pList->Name = Name;
pList->Next = NULL;
}
void AddItemToList(struct List *pList, struct Person *NewPerson)
{
struct Person * Last;
if (pList->Next == NULL)
{
pList->Next = NewPerson;
NewPerson->Next =NULL;
return;
}
Last = pList->Next;
while (Last->Next)
{
Last = Last->Next;
}
Last->Next = NewPerson;
NewPerson->Next = NULL;
}
void DelItemFromList(struct List *pList, struct Person * CurPerson)
{
struct Person *P = pList->Next;
struct Person *Pre = NULL;
while (P != NULL && P != CurPerson)
{
Pre = P;
P = P->Next;
}
if (P == NULL)
{
printf("can not find the person to del\r\n");
return;
}
if (Pre == NULL)
{
pList->Next = P->Next;
}
else
{
Pre->Next = P->Next;
}
}
void SortList(struct List * pList)
{
struct Person * Pre;
struct Person * Next;
char * TempName;
int TempAge;
Pre = pList->Next;
if (Pre == NULL)
return;
while (Pre)
{
Next = Pre->Next;
while (Next)
{
if (Pre->Age > Next->Age)
{
TempName = Pre->Name;
Pre->Name = Next->Name;
Next->Name = TempName;
TempAge = Pre->Age;
Pre->Age = Next->Age;
Next->Age = TempAge;
}
Next = Next->Next;
}
Pre = Pre->Next;
}
}
void PrintList(struct List *pList)
{
int i = 0;
struct Person *P = pList->Next;
while (P != NULL)
{
printf("Person %d: %s is %d\r\n", i++, P->Name, P->Age);
P = P->Next;
}
}
int main(void)
{
struct List A_List;
int i = 0;
struct Person P[] = {
{"P0", 19, NULL},
{"P1", 11, NULL},
{"P2", 17, NULL},
{"P3", 13, NULL},
{"P4", 18, NULL},
{"P5", 15, NULL},
{"P6", 16, NULL},
{"P7", 12, NULL},
{NULL, 0, NULL},
};
InitList(&A_List, "A_class");
while (P[i].Name != NULL)
{
AddItemToList(&A_List, &P[i]);
i++;
}
PrintList(&A_List);
DelItemFromList(&A_List, &P[3]);
printf("del person %s:\r\n", P[3].Name);
PrintList(&A_List);
DelItemFromList(&A_List, &P[0]);
printf("del person %s:\r\n", P[0].Name);
PrintList(&A_List);
SortList(&A_List);
printf("sort list, all person:\r\n");
PrintList(&A_List);
return 0;
}
