C语言用链表删除学生信息
时间: 2024-02-28 07:53:59 浏览: 24
好的,我可以帮你解释一下代码的实现过程:
首先,需要定义一个结构体来存储学生信息,包括学生的ID、姓名、性别、班级、出生日期、电话号码和家庭住址。然后,我们可以定义一个链表,用来存储多个学生的信息。
接着,我们可以实现链表的基本操作,包括创建链表、添加学生信息、显示所有学生信息以及删除指定学生信息。
具体实现过程如下:
```c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _student{
int ID;
char name[20];
char sex[5];
char Class[20];
char date[20];
char Tel[20];
char home[20];
}student;
typedef struct _node{
student data;
struct _node *next;
}node;
// 创建链表
node *createList() {
node *head,*p;
head = p = (node*)malloc(sizeof(node));
p->next = NULL;
return head;
}
// 添加学生信息
void addStudent(node *head, student *newStu) {
node *p, *q;
p = head;
while(p->next != NULL) {
p = p->next;
}
q = (node*)malloc(sizeof(node));
q->data = *newStu;
q->next = p->next;
p->next = q;
}
// 显示所有学生信息
void displayList(node *head) {
node *p;
p = head->next;
while(p != NULL) {
printf("%d\t%s\t%s\t%s\t%s\t%s\t%s\n", p->data.ID, p->data.name, p->data.sex, p->data.Class, p->data.date, p->data.Tel, p->data.home);
p = p->next;
}
}
// 删除指定学生信息
void deleteStudent(node *head, int ID) {
node *p, *q;
p = head->next;
while(p != NULL && p->data.ID != ID) {
q = p;
p = p->next;
}
if(p == NULL) {
printf("No student with ID %d exists.\n", ID);
}
else {
q->next = p->next;
free(p);
printf("Student with ID %d has been deleted.\n", ID);
}
}
int main() {
node *head;
student newStu;
int choice, ID;
char name[20], sex[5], Class[20], date[20], Tel[20], home[20];
head = createList();
do {
printf("Menu:\n");
printf("1. Add student\n");
printf("2. Display all students\n");
printf("3. Delete student\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter student ID: ");
scanf("%d", &newStu.ID);
printf("Enter student name: ");
scanf("%s", &newStu.name);
printf("Enter student sex: ");
scanf("%s", &newStu.sex);
printf("Enter student class: ");
scanf("%s", &newStu.Class);
printf("Enter student date of birth: ");
scanf("%s", &newStu.date);
printf("Enter student telephone number: ");
scanf("%s", &newStu.Tel);
printf("Enter student home address: ");
scanf("%s", &newStu.home);
addStudent(head, &newStu);
break;
case 2:
displayList(head);
break;
case 3:
printf("Enter student ID to delete: ");
scanf("%d", &ID);
deleteStudent(head, ID);
break;
case 4:
printf("Exiting program...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
} while(choice != 4);
return 0;
}
```
以上就是用链表删除学生信息的C语言代码实现过程。