使用LINUX C实现一个链表,要求:链表节点构成:姓名、分数、下一个节点指针...

来源:互联网 发布:没什么用网络语怎么说 编辑:程序博客网 时间:2024/06/03 16:00
使用LINUX C实现一个链表,要求:(共30分)
(1) 链表节点构成:姓名、分数、下一个节点指针;(9分)
(2) 构建完成链表节点数据输入,至少5个节点数据; (9分)

(3) 保存链表数据到文件操作; (9分)

----------------------------------------------------------------------------------------------------------------

// A.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>#include "string.h"#include "stdlib.h"//使用LINUX C实现一个链表,要求:(共30分)//(1) 链表节点构成:姓名、分数、下一个节点指针;(9分)//(2) 构建完成链表节点数据输入,至少5个节点数据; (9分)//(3) 保存链表数据到文件操作; (9分)//链表节点定义struct student{   char name[20];//姓名   int score;//分数   struct student *next;//下一个节点指针};void main (){struct student  *pHead;//链头struct student  *pEnd;//链尾struct student  *pNew;//新节点//创建链头和链尾 pHead=(struct student *)malloc(sizeof(struct student)); pEnd=pHead; pEnd->next=0;//链尾标志 //输入链头数据 printf("请输入学生姓名:"); scanf("%s",pHead->name); printf("请输入学生分数:"); scanf("%d",&pHead->score);//注意不能少取地址符&,不然程序崩溃 int i=1; while (++i<=5) { pNew=(struct student *)malloc(sizeof(struct student));//新节点 //输入新节点数据 printf("\n请输入学生姓名:"); scanf("%s",pNew->name); printf("请输入学生分数:"); scanf("%d",&pNew->score);//注意不能少取地址符&,不然程序崩溃 //把新节点数据放入链尾 pEnd->next=pNew; //更新链尾 pEnd=pNew; pEnd->next=0;//链尾标志 } //遍历链表,保存链表数据到文件printf("\n\n");FILE *pFile;if((pFile=fopen("C:\\student.txt","wb+"))==NULL){printf("保存文件出错!\n");exit(0);//退出程序}struct student  *pTmp=pHead;while(pTmp){//printf("name:%s score:%d\n",pTmp->name,pTmp->score);//pTmp=pTmp->next;//下一节点//将分数转成字符串,为保存做准备char s[25];itoa(pTmp->score,s,10);fputs(pTmp->name,pFile);//保存姓名fputs("---",pFile);//分隔符fputs(s,pFile);//保存分数fputs("\r\n",pFile);//换行pTmp=pTmp->next;//下一节点}fclose(pFile);//关闭打开的文件printf("学生信息已保存在C:\\student.txt,按任意键退出程序!...\n");getchar();//暂停程序getchar();//暂停程序 }

---------------------------------------------------------------------------------------------------------------------------------------------------------




----------------------------------------------------------------------------------------------------------------------------------------------------


您的十分满意是我追求的宗旨。

您的一点建议是我后续的动力。






0 0
原创粉丝点击