0
点赞
收藏
分享

微信扫一扫

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


使用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();//暂停程序
}


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

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


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

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

​​​​

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

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






举报

相关推荐

0 条评论