代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h>
struct node {
char name[20];
int age;
struct node *ptrnext;
};
//1.读取文件并创建链表
struct node* ReadFile()
{
struct node* head = 0;
FILE* fp;
struct node* p = 0,*cur = 0;
head = 0;
if (!(fp = fopen("FP.txt","r")))
{
printf("file open error\n");
return 0;
}
//逐行读取文件
while(!feof(fp))
{
p = new node;
p->name[0] = 0;
fscanf(fp,"%s\t%d",p->name,&p->age);
p->ptrnext = 0;
//加上这段代码
if (p->age < 0 ||p->age > 200)
{
delete p;
continue;
}
if(head == 0)
{
head = p;
cur = head;
}
else
{
cur->ptrnext = p;
cur = p;
}
}
fclose(fp);
return head;
}
//2.打印所有元素
void Display(struct node* head)
{
struct node* ss = head;
while(ss)
{
printf("%s\t%d\n",ss->name,ss->age);
ss= ss->ptrnext;
}
}
//3.改变链表的方式
void ChangeList(struct node* p_head)
{
node *pb, *pf, temp;
pf = p_head;
if(p_head == 0)
return ;
if(p_head->ptrnext == 0)
return ;
while(pf->ptrnext != 0) {//以pf指向的节点为基准节点
pb = pf->ptrnext;//pb从基准点的下一个节点开始
while(pb != NULL) {
if(pf->age > pb->age) {
temp = *pf;
*pf = *pb;
*pb = temp;
temp.ptrnext = pf->ptrnext;
pf->ptrnext = pb->ptrnext;
pb->ptrnext = temp.ptrnext;
}
pb = pb->ptrnext;
}
pf = pf->ptrnext;
}
return ;
}
//4.删除给定年龄的一组元素
void DeleteNode(struct node* head)
{
int age;
struct node* prenode = 0;
struct node* curnode = 0;
struct node* tmp = 0;
printf("请输入需要删除的年龄组:");
scanf("%d",&age);
while (head->age == age)
{
curnode = head->ptrnext;
delete head;
head = curnode;
}
prenode = head;
curnode = prenode->ptrnext;
while(curnode)
{
if (curnode->age == age)
{
tmp = curnode->ptrnext;
delete curnode;
curnode = tmp;
prenode->ptrnext = curnode;
}else
{
prenode = curnode;
curnode = curnode->ptrnext;
}
}
}
//5.写入文件
void WriteFile(struct node* head)
{
struct node* pp = head;
FILE* fp;
if (!(fp = fopen("FX.txt","w")))
{
printf("FX.txt打开失败\n");
return ;
}
while(pp)
{
fprintf(fp,"%s\t%d\n",pp->name,pp->age);
pp = pp->ptrnext;
}
fclose(fp);
}
//6.删除链表
void DeleteList(struct node* head)
{
struct node* pp;
while(head)
{
pp = head->ptrnext;
delete head;
head = pp;
}
}
int main()
{
struct node* head = 0;
//1.从文件读取并创建链表
head = ReadFile();
//2.显示所有元素
Display(head);
//3.改变列表方式
ChangeList(head);
printf("排序后\n");
Display(head);
//4.删除年龄组
DeleteNode(head);
//5.复制到文件FX
WriteFile(head);
//6.删除链表
DeleteList(head);
return 0;
}
FP.txt文件内容如下(名字和年龄之间使用tab键分隔):
John 34
Tremblay 23
Jessica 27
Djamal 22
Didier 33
Liu 37
Yang 23
Johnathan 34
Talbi 23
Jasmine 27
Lola 22
Diderot 33
Lee 37
Sebastien 23
Lewis 34
Lila 23
Jessy 27
Mary 22
Davidson 33
Chang 37
Mouloud 23
Meziane 34
Ali 23
Mohand 27
Djamila 22
Ouiza 33
Louize 37
Fabio 23
Jack 34
Zilenski 23
Tarik 27
Samy 22
Sarah 33
Lee 37
Alain 23
Johnson 34
Brian 23
Jordan 27
Gilbert 22
George 23
Harrison 27
Thierno 23
Mamadou 33
Simard 27
Jerry 27
Sofia 27
Victor 27
Victoria 27
Philip 23
Steve 27
Francois 23
Allard 27
Julien 23
Jules 33
Peter 34
Samson 34