用c语言建立一个链表,每个节点包括:学号、姓名、性别、年龄。
时间: 2023-07-10 22:28:22 浏览: 203
C语言课程设计
好的,下面是建立链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表节点结构体
typedef struct student {
int number;
char name[20];
char sex;
int age;
struct student *next;
} Student;
// 初始化链表
Student *initList() {
Student *head = (Student*)malloc(sizeof(Student));
head->next = NULL;
return head;
}
// 添加节点
void addNode(Student *head, int number, char name[], char sex, int age) {
Student *p = (Student*)malloc(sizeof(Student));
p->number = number;
strcpy(p->name, name);
p->sex = sex;
p->age = age;
p->next = NULL;
Student *q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
}
// 删除节点
void deleteNode(Student *head, int number) {
Student *p = head->next;
Student *q = head;
while (p != NULL) {
if (p->number == number) {
q->next = p->next;
free(p);
return;
}
q = p;
p = p->next;
}
}
// 修改节点
void modifyNode(Student *head, int number, char name[], char sex, int age) {
Student *p = head->next;
while (p != NULL) {
if (p->number == number) {
strcpy(p->name, name);
p->sex = sex;
p->age = age;
return;
}
p = p->next;
}
}
// 查询节点
void searchNode(Student *head, int number) {
Student *p = head->next;
while (p != NULL) {
if (p->number == number) {
printf("学号:%d\n", p->number);
printf("姓名:%s\n", p->name);
printf("性别:%c\n", p->sex);
printf("年龄:%d\n", p->age);
return;
}
p = p->next;
}
printf("查无此人!\n");
}
// 输出链表
void printList(Student *head) {
Student *p = head->next;
while (p != NULL) {
printf("学号:%d\n", p->number);
printf("姓名:%s\n", p->name);
printf("性别:%c\n", p->sex);
printf("年龄:%d\n", p->age);
printf("\n");
p = p->next;
}
}
int main() {
Student *head = initList();
addNode(head, 1001, "小明", 'M', 18);
addNode(head, 1002, "小红", 'F', 19);
addNode(head, 1003, "小刚", 'M', 20);
printList(head);
deleteNode(head, 1002);
printList(head);
modifyNode(head, 1001, "小明明", 'M', 19);
printList(head);
searchNode(head, 1003);
return 0;
}
```
这个程序实现了链表的基本操作,包括初始化链表、添加节点、删除节点、修改节点、查询节点和输出链表。你可以在此基础上进行修改,实现你所需的功能。
阅读全文