链表操作

来源:互联网 发布:林肯mac 编辑:程序博客网 时间:2024/06/06 09:48
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"student.h"
student*head;
void main(){
head = (student*)malloc(sizeof(student));
head->next = NULL;
char a[] = "students.txt";
char b[] = "output.txt";
char c[] = "delete.txt";
char d[] = "update.txt";
ReadInputFile(a);
PrintfToFile(b);
ProcessDeleteFile(c);//删除相应学号的学生;
PrintfToFile(d);
free(head);
}
void ReadInputFile(char*filename){
student*tmp;
FILE*fp = fopen(filename, "r");
if (fp == NULL){
printf("Error:can't open the file");
}
else{
while (!feof(fp)){
tmp = (student*)malloc(sizeof(student));
fscanf(fp, "%s", tmp->Firstname);
fscanf(fp, "%s", tmp->Lastname);
fscanf(fp, "%s", tmp->SSN);
fscanf(fp, "%d", &tmp->CoureAtNum);
for (int i = 0; i < tmp->CoureAtNum; i++){
fscanf(fp, "%s%d%d", tmp->mycourse[i].Coursename, &tmp->mycourse[i].CourseID,&tmp->mycourse[i].Coursesection);
}
tmp->next = NULL;
AddToList(tmp);//添加链表
tmp = NULL;
free(tmp);
}
}
fclose(fp);
}
void AddToList(student*addStudent){
student*tmp;//定义临时变量存储形参
tmp = (student*)malloc(sizeof(student));
tmp= addStudent;
if (!head->next){
head->next = tmp;
}                       //若头结点下一个为空则进行赋值;
else{
student*Node = head->next;
while (Node->next){
Node = Node->next;
}
Node->next = tmp;//将临时变量的值赋给下一个结点;
}
tmp = NULL;
free(tmp);//释放临时变量的内存;
}
void PrintfToFile(char*FileName){
FILE*fp = fopen(FileName, "w");
if (fp){
student*tmp=(student*)malloc(sizeof(student));
tmp = head->next;//从头结点下一个结点开始读
{
while (tmp){//但结点非空时循环读入
fprintf(fp, "%s\n", tmp->Firstname);
fprintf(fp, "%s\n", tmp->Lastname);
fprintf(fp, "%s\n", tmp->SSN);
fprintf(fp, "%d\n", tmp->CoureAtNum);
for (int i = 0; i < tmp->CoureAtNum; i++){
fprintf(fp, "%s  %d  %d\n", tmp->mycourse[i].Coursename, tmp->mycourse[i].CourseID, tmp->mycourse[i].Coursesection);
}
tmp = tmp->next;
}
}
free(tmp);
}
else
{
printf("没有定义指针\n");
}
fclose(fp);
}
void ProcessDeleteFile(char*FileName){
FILE*fp = fopen(FileName, "r");
char SSN[15] = {'\0'};
if (!fp){
printf("Error: can't find the File");
}
while (!feof(fp)){
fscanf(fp, "%s", SSN);
DeleteStudent(SSN);
}
fclose(fp);
}
void DeleteStudent(char*SSN){
student*Search = (student*)malloc(sizeof(student));
student*prev = (student*)malloc(sizeof(student));
Search = head->next;
prev = head; //定义临时指针指向Search的前一个
while (strcmp(Search->SSN,SSN)!=0)
{
prev = Search;
Search = Search->next;
}
prev->next = Search->next;
Search = NULL;
prev = NULL;
free(Search);
free(prev);
}
void DeleteList(void){
student*Node=(student*)malloc(sizeof(student));
Node = head->next;
while (Node){
student*tmp = (student*)malloc(sizeof(student));
tmp = Node;
Node = Node->next;
free(tmp);
}
free(Node);
}