C语言 文件操作+线性链表+冒泡/直接排序实验室

文件操作+线性链表+冒泡/直接排序实验室。
现有结构体定义如下:
struct stuInfo
{
char id[12]; //数据成员
char name[15];
float score;

struct stuInfo *next; //指针成员

}
任务及要求:
(1)首先完成线性链表的定义和创建,确保链表的第一个节点为哨兵节点,不存放有效的数据;
(2)利用文件的相关操作,动态开辟节点存储空间,将存放在磁盘某个路径中的文件“stuinfo.txt”信息逐条读入,并依次存入到线性链表的每个节点中,信息如下;
00001 张三 100
00002 李四 99
00003 王五 100
00004 王六 89
00005 江涛 98
00006 陈琪 88
00007 祁廷 911
(3)接下来,将学号为‘00004’的节点删除;
(4)再接下来,利用冒泡排序,对链表继续升序排序;(5)将完整的线性链表信息从头到尾依次存储到磁盘某个路径下的“score.txt”文件中,存储格式和“stuinfo.txt”文件相同。

#include <stdio.h>
#include <stdlib.h>
#include<String>

typedef struct _STUINFO
{
	char id[12];
	char name[15];
	float score;
	_STUINFO *next;
}STUINFO;

void createStuInfo(STUINFO *head)
{
	STUINFO *p = head;
	FILE *fp = fopen("stuinfo.txt","r");
	if(fp == NULL)
		return;
	char buf[100];
	while(fgets(buf,100,fp))
	{
		STUINFO *q = (STUINFO*)malloc(sizeof(STUINFO));
		sscanf(buf,"%s %s %f",q->id,q->name,&q->score);
		q->next = NULL;
		p->next = q;
		p = q;
	}
	fclose(fp);
}

void delStuInfo(STUINFO *head,char *id)
{
	if(head == NULL)
		return;
	
	STUINFO *p = head->next;
	STUINFO *q = head;
	while(p != NULL)
	{
		if(strcmp(p->id,id) == 0)
		{
			q->next = p->next;
			free(p);
			return;
		}
		q = p;
		p = p->next;
	}
}

void saveStuInfo(STUINFO *head)
{
	if(head == NULL)
		return;
	FILE *fp = fopen("score.txt","w");
	if(fp == NULL)
		return;
	STUINFO *p = head->next;
	while(p != NULL)
	{
		fprintf(fp,"%s %s %g\n",p->id,p->name,p->score);
		p = p->next;
	}
	fclose(fp);
}


void  BubbleSort(STUINFO* head)
{
	if(head == NULL || head->next == NULL)
		return;
	STUINFO *t = NULL;
	while (t != head->next->next)
	{
		STUINFO *p = head->next;
		while (p->next != NULL)
		{
			if (p->score > p->next->score)
			{
				STUINFO s;
				strcpy(s.id,p->id);
				strcpy(s.name,p->name);
				s.score = p->score;
				strcpy(p->id,p->next->id);
				strcpy(p->name,p->next->name);
				p->score = p->next->score;
				strcpy(p->next->id,s.id);
				strcpy(p->next->name,s.name);
				p->next->score = s.score;
			}
			if(p->next->next == t)
			{
				t = p->next;
				break;
			}
			p = p->next;
		}
	}
}

void insertMin(STUINFO *head,STUINFO *p){
	//pp为链表的前节点,qq为链表的后节点 
	STUINFO *pp,*qq;
	qq=head;
	pp=head->next;
	while(pp){
		if(pp->score>p->score)
			break;
		qq=pp;//后面的节点向前移动 
		pp=pp->next;//前面的节点向前移动 
	}
	//连线插入节点 
	p->next=pp;
	qq->next=p;
}
void insertsort(STUINFO *head){
	STUINFO *p,*q;
	p=head->next;
	head->next=NULL;
	while(p){
		q=p->next;
		p->next=NULL;
		insertMin(head,p);
		p=q;
	}
 }

void print(STUINFO * head)
{
	if(head == NULL)
		return;
	STUINFO* p = head->next;
	while(p != NULL)
	{
		printf("%s %s %f\n",p->id,p->name,p->score);
		p = p->next;
	}
}

void main()
{
	STUINFO *head = (STUINFO*)malloc(sizeof(STUINFO));
	createStuInfo(head);
	delStuInfo(head,"00004");
	//BubbleSort(head);
	insertsort(head);
	saveStuInfo(head);
	print(head);
	system("pause");
}

上一篇:MySQL的简单总结


下一篇:MySQL常见约束