C语言链表基本操作:创建 删除 插入 输出
- 题目示例:输入学号、姓名、成绩(创建);留下不及格的同学也就是删除及格的同学(删除);增加一个同学的信息(插入);输出不及格的同学(输出)。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student{
int num;
char name[20];
int score;
struct student *next;
};
struct student *Creat_Stu_Doc();
struct student *Delet_Doc(struct student *head);
struct student *Add_Doc(struct student *head,int index);
void Print_Stu_Doc(struct student *head);
int main(void)
{
struct student *head;
head = Creat_Stu_Doc();
head = Delet_Doc(head);
int index;
printf("想在第几位同学后面添加信息?(0即使开头)");
index = scanf("%d",&index);
head = Add_Doc(head,index);
Print_Stu_Doc(head);
return 0;
}
struct student *Creat_Stu_Doc()
{
struct student *head,*tail,*p;
int num,score;
char name[20];
int size = sizeof(struct student);
head = tail = NULL;
scanf("%d",&num);
while (num!=0){
scanf("%s%d",name,&score);
p = (struct student*)malloc(size);
p->num = num;
p->score = score;
strcpy(p->name,name);
p->next = NULL;
if (head==NULL){
head = p;
}
else{
tail->next = p;
}
tail = p;
scanf("%d",&num);
}
return head;
}
struct student *Delet_Doc(struct student *head)
{
if(head==NULL){
return NULL;
}
struct student *ptr1,*ptr2;
while(head->score>=60){
ptr2 = head;
head = head->next;
free(ptr2);
}
ptr1 = head;
ptr2 = head->next;
while(ptr2!=NULL){
if (ptr2->score>=60){
ptr1->next = ptr2->next;
free(ptr2);
}
else{
ptr1 = ptr2;
}
ptr2 = ptr1->next;
}
return head;
}
struct student *Add_Doc(struct student *head,int index){
struct student *ptr1,*ptr2,*p;
int size = sizeof(struct student);
int num,score;
char name[20];
scanf("%d%s%d",&num,name,&score);
p = (struct student*)malloc(size);
p->num = num;
p->score = score;
strcpy(p->name,name);
if(index==0){
ptr2 = head;
head = p;
head->next = ptr2;
return head;
}
else{
ptr1 = head;
ptr2 = head->next;
for(int i = 1;i<index;i++){
ptr1 = ptr2;
ptr2 = ptr1->next;
}
p->next = ptr1->next;
ptr1->next = p;
return head;
}
}
void Print_Stu_Doc(struct student *head)
{
struct student *tmp;
if (head==NULL){
printf("There is no record");
return;
}
for(tmp=head;tmp;tmp = tmp->next)
{
printf("%d %s %d\n",tmp->num,tmp->name,tmp->score);
}
}