单向链表实现
#include <stdio.h>
#include <malloc.h>typedef int DATA;struct SNode
{DATA data;SNode* pNext;
};
SNode* g_pHead = NULL;void AddHead(DATA data)
{SNode* p = (SNode*)malloc(sizeof(SNode));p->data = data;p->pNext = g_pHead;g_pHead = p;
}void AddTail(DATA data)
{SNode* pNew = (SNode*)malloc(sizeof(SNode));pNew->data = data;pNew->pNext = NULL;if (!g_pHead){g_pHead = pNew;return;}SNode* p = g_pHead;while (p->pNext)p = p->pNext;p -> pNext = pNew;
}void Print()
{SNode* p = g_pHead;while (p){printf("%d ", p->data);p = p->pNext;}
}int main()
{AddHead(3);AddHead(2);AddHead(1);return 0;
}
学生管理系统_单向链表内操作
- 只实现了
按学号排序SortByNumb
函数,按姓名、数学成绩排序实现类似,可参考前序文章,不做赘述。 - 单向链表内操作,意思是排序时对链表内部数据直接进行排序,会改变链表内容。
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>
#include <string.h>
#include <stdlib.h>typedef struct SUser
{int nNumb;char sName[20];float fMath;
}DATA;struct SNode
{DATA data;SNode* pNext;
};SNode* g_pHead = NULL;void AddTail(DATA data)
{SNode* pNew = (SNode*)malloc(sizeof(SNode));pNew->data = data;pNew->pNext = NULL;if (!g_pHead){g_pHead = pNew;return;}SNode* p = g_pHead;while (p->pNext)p = p->pNext;p->pNext = pNew;
}void AddHead(DATA data)
{SNode* p = (SNode*)malloc(sizeof(SNode));p->data = data;p->pNext = g_pHead;g_pHead = p;
}void Load()
{DATA data;FILE* pf = fopen("stud.lv", "r");if (!pf){puts("加载信息时失败!");return;}while (fread(&data, 1, sizeof(DATA), pf) == sizeof(DATA)){AddTail(data);}fclose(pf);
}void Save()
{SNode* p = g_pHead;FILE* pf = fopen("stud.lv", "w");if (!pf){puts("保存文件时失败!");return;}while (p){fwrite(p, 1, sizeof(p->data), pf);p = p->pNext;}fclose(pf);
}void Print()
{system("cls");puts("学号\t姓名\t成绩");int i = 0;SNode* p = g_pHead;while (p){printf("%d\t%s\t%0.1f\n", p->data.nNumb,p->data.sName,p->data.fMath);p = p->pNext;++i;}printf("\t总共有 %d 条记录\n", i);system("pause");
}void Input(int nDir)
{int nNumb;printf("请输入学号:");scanf_s("%d", &nNumb);DATA data;data.nNumb = nNumb;printf("请输入姓名:");scanf_s("%s", data.sName, sizeof(data.sName));printf("请输入成绩:");scanf_s("%f", &data.fMath);if (1 == nDir)AddHead(data);elseAddTail(data);Save();Print();
}int AddMenu()
{puts("1.向头部插入");puts("2.向尾部插入");puts("0.返回主菜单");int i = 0;scanf_s("%d", &i);switch (i){case 1:case 2:Input(i);break;}return i;
}void SortByNumb()
{SNode* p = g_pHead;if (!p)return;while (p->pNext){SNode* q = p->pNext;SNode* m = p;while (q){if (q->data.nNumb < m->data.nNumb)m = q;q = q->pNext;}if (m != p){DATA t = p->data;p->data = m->data;m->data = t;}p = p->pNext;}
}int SortMenu()
{system("cls");puts("1.按学号排序");puts("2.按姓名排序");puts("3.按成绩排序");puts("0.返回主菜单");int i = 0;scanf_s("%d", &i);switch (i){case 1:SortByNumb();break;case 2:break;case 3:break;default:return i;}Print();return i;
}int Menu()
{int i = 0;system("cls");puts("1.浏览所有信息");puts("2.添加信息");puts("3.删除信息");puts("4.修改信息");puts("5.查找信息");puts("6.颜色设置");puts("0.退出");printf("请选择:");scanf_s("%d", &i);switch (i){case 0:break;case 1:while (SortMenu());break;case 2:while (AddMenu());break;}return i;
}int main()
{Load();while (Menu());return 0;
}