|
楼主 |
发表于 2020-5-11 10:21:05
|
显示全部楼层
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//学生结构
struct STU
{
char stunum[10];
char stuname[20];
int stuage;
};
//把所有要处理的数据改为我们的数据
struct Node
{
struct STU data;
struct Node* next;
};
//创建一个表头
struct Node* creatList()
{
struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));
headNode->next = NULL;
return headNode;
};
//创建节点
struct Node* createNode(struct STU data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->next = NULL;
newNode->data = data;
return newNode;
};
void insertNodeByHead(struct Node* headNode, struct STU data)
{
struct Node* newNode = createNode(data);
newNode->next = headNode->next;
headNode->next = newNode;
}
void bubbleSortListByNum(struct Node* headNode)//冒泡排序法,按学号升序这个有待调试
{
struct Node* p1, *p2, *p3, *p4, *p5, *pMove;
p1 = p3= p5=headNode;
p2 = headNode->next;
p4 = NULL;
while (p3->next!=NULL)
{
if (p1->data.stunum > p2->data.stunum)
{
p1->next = p2->next;
p2->next = p1;
p2 = p1->next;
}
else
{
p1 = p1->next;
p2 = p2->next;
}
p4 = p2;
while (p4->data.stunum)
{
if (p1->data.stunum > p2->data.stunum)
{
p1->next = p2->next;
p2->next = p1;
p2 = p1->next;
}
else
{
p1 = p1->next;
p2 = p2->next;
}
p4 = p4->next;
}
p3 = p3->next;
p1 = p3;
p2 = p3->next;
}
pMove = p5->next;//打印排序后的结果
while (pMove)
{
printf("%s\t%s\t\t%d\n", pMove->data.stunum, pMove->data.stuname, pMove->data.stuage);
pMove = pMove->next;
}
printf("\n");
}
//读文件
void readInfoFromFile(struct Node* list, char *filename)//打开文件
{
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
fp = fopen(filename, "w+");
}
struct STU tempInfo;
while (fscanf(fp, "%s\t%s\t%d\n", tempInfo.stunum, tempInfo.stuname, &tempInfo.stuage) != EOF)
{
insertNodeByHead(list, tempInfo);
}
fclose(fp);
}
void saveInfoToFile(struct Node* headNode, char *filename)//编辑并保存文件
{
FILE *fp = fopen(filename, "w");
struct Node* pMove = headNode->next;
while (pMove)
{
fprintf(fp, "%s\t%s\t%d\n", pMove->data.stunum, pMove->data.stuname, pMove->data.stuage);
pMove = pMove->next;
}
fclose(fp);
}
struct Node* list = NULL;
void drawMenu()
{
printf(" 欢迎进入数据系统\n");
printf(" 0.退出系统\n");
printf(" 1.录入信息\n");
printf(" 2.按照学号冒泡排序\n");
printf(" 请输入0—2:");
}
void keyDown()
{
int userKey = 0;
struct STU stu;
struct Node* posNode = NULL;
scanf("%d", &userKey);
switch (userKey)
{
case 0:
printf("已退出\n");
system("pause");
exit(0);
break;
case 1:
printf(" 录入学生信息\n");
printf(" 请输入:stunum,name,stuage(以空格隔开):");
scanf("%s%s%d", stu.stunum, stu.stuname, &stu.stuage);
insertNodeByHead(list, stu);
saveInfoToFile(list, "student.txt");
break;
case 2:
printf(" 排序结果\n");
bubbleSortListByNum(list);
break;
default:
printf(" 输入错误,请重新输入\n");
}
}
int main()
{
list = creatList();
readInfoFromFile(list, "student.txt");
while (true)
{
drawMenu();
keyDown();
system("pause");
system("cls");//清屏
}
return 0;
}
|
|