










1、根据教师信息的格式构建结构体,为创建链表做准备
typedef struct teacher {//根据文件之中每条信息的格式,建立结构体,数据类型得具体按照题意设置
char workNum[10];
int sex;
char name[20];
int year;
teacher* next;
}teacher;
2、打开文件
FILE* fp = fopen("input.txt", "r");//fopen,传入文件名称,读写方式,返回一个file类型的指针
3、用格式化fscaf读取数据
注意:%s不用&符号,%d需要&符号,和scanf规则一致
fscanf(fp, "%s,%d,%s,%d", tmp->workNum, &tmp->sex, tmp->name, &tmp->year);
4、判断是否读取完毕
if (feof(fp)) {//判断是否读取完毕
break;
}
5、最后一定要把文件关闭
fclose(fp); //记得关闭文件,否则可能会是扣分点(有开就有关)
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef struct teacher {//根据文件之中每条信息的格式,建立结构体,数据类型得具体按照题意设置
char workNum[10];
int sex;
char name[20];
int year;
teacher* next;
}teacher;
teacher* function_three() {
FILE* fp = fopen("input.txt", "r");//fopen,传入文件名称,读写方式,返回一个file类型的指针
teacher* head = (teacher*)malloc(sizeof(teacher));//建立哨兵节点(利用头插法,少一个指针,方便控制)
while (1) {//开始读取数据
teacher* tmp = (teacher*)malloc(sizeof(teacher));//建立节点,准备接收数据
//用fscanf读取数据,参数文件指针,后两项和scanf一样
fscanf(fp, "%s,%d,%s,%d", tmp->workNum, &tmp->sex, tmp->name, &tmp->year);
if (feof(fp)) {//判断是否读取完毕
break;
}
//开始头插法,插入到哨兵节点后面
tmp->next = head->next;
head->next = tmp;
}
fclose(fp); //记得关闭文件,否则可能会是扣分点(有开就有关)
return head;
}
1、链表创建
<1>先在外面建立好哨兵
<2>再循环建立节点,头插法插入
2、分割链表
<1>准备好新链表表头哨兵
<2>从原来链表上开始遍历(双指针法),遇到需要拆分的,把节点先拆下来,把原本的链安好,再把这个节点头插法进新的链表
3、写入文件
<1>总体思路:打开-写入-关闭
<2>使用函数:fprintf格式化写入,fopen打开文件,fclose关闭文件
#include
#include
#include
#include
#include
#include
#include
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
struct node {
int val;
node* next;
};
void function_five() {
int n = 0;
cin >> n;
//创建链表
node *head = (node*)malloc(sizeof(node));//哨兵
head->next = nullptr;
for (int i = 0; i < n; i++) {
node *tmp = (node*)malloc(sizeof(node));
cin >> tmp->val;
tmp->next = head->next;//头插法
head->next = tmp;
}
//分割链表(仅练习,用奇偶性)
node *ano = (node*)malloc(sizeof(node));//连接奇数项
ano->next = nullptr;
node *pre = head, *cur = head->next;
while (cur != nullptr) {
if (cur->val % 2 != 0) {
node* tmp = cur;//从原链表中拆下来
cur = cur->next;
pre->next = cur;
tmp->next = ano->next;//把该节点头插法进入ano的新链表
ano->next = tmp;
}
}
//写入文件(打开-操作-关闭)
FILE* fp1 = fopen("****.txt", "w");
FILE* fp2 = fopen("****.txt", "w");
node *c = head->next, *q = ano->next;//因为有哨兵
while (c != nullptr) {
fprintf(fp1, "%d", c->val);
}
while (q != nullptr) {
fprintf(fp2, "%d", q->val);
}
fclose(fp1);
fclose(fp2);
return;
}