头插法、尾插法、有序插入
#include <stdio.h>
#include<stdlib.h>
typedef struct student {
int num;
float score;
struct student* pnext;
}stu, * pstu;
void list_head_insert(pstu* pphead, stu** pptail, int i) {
pstu pnew = (pstu)malloc(sizeof(stu));
pnew->num = i;
pnew->pnext = NULL;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; }
else { pnew->pnext = *pphead; *pphead = pnew; }
}
void list_tail_insert(pstu* pphead, stu** pptail, int i) {
pstu pnew = (pstu)calloc(1, sizeof(stu));
pnew->num = i;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; }
else {(*pptail)->pnext = pnew; *pptail = pnew; }
}
void list_print(pstu phead)
{
while (phead)
{
printf("%d ", phead->num);
phead = phead->pnext;
}
}
void list_sort_insert(pstu* pphead, stu** pptail, int i) {
pstu pnew = (pstu)calloc(1, sizeof(stu));
pnew->num = i;
pstu pcur, ppre;
pcur = ppre = *pphead;
if (*pphead == NULL) { *pphead = pnew; *pptail = pnew; }
else if (i < (*pphead)->num) { pnew->pnext = *pphead; *pphead = pnew; }
else {
while (pcur) {
if (i > (pcur->num)) { ppre = pcur; pcur = pcur->pnext; }
else { ppre->pnext = pnew; pnew->pnext = pcur; break; }
}
if(pcur==NULL){ (*pptail)->pnext = pnew; *pptail = pnew; }
}
}
int main() {
pstu phead = NULL, ptail = NULL;
int i;
while (scanf_s("%d", &i) != EOF)
{
list_sort_insert(&phead, &ptail, i);
}
list_print(phead);
return 0;
}