链表的增删改查
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char name[20];
int age;
struct node* next;
};
void addstudent(struct node** head, const char* name, int age) {
struct node* newstudent = (struct node*)malloc(sizeof(struct node));
if (newstudent == NULL) {
printf("内存分配失败\n");
return;
}
strcpy(newstudent->name, name);
newstudent->age = age;
newstudent->next = NULL;
if (*head == NULL)
*head = newstudent;
else {
struct node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newstudent;
}
}
struct node* findstudent(struct node* head, const char* name) {
struct node* p = head;
while (p != NULL && strcmp(p->name, name) != 0) {
p = p->next;
}
if (p == NULL)
return NULL;
else
return p;
}
void updatestudent(struct node* head, const char* oldname, const char* newname, int newage) {
struct node* student = findstudent(head, oldname);
if (student != NULL) {
strcpy(student->name, newname);
student->age = newage;
} else
printf("未找到名为%s的学生\n", oldname);
}
void deletestudent(struct node** head, const char* name) {
struct node* temp = *head;
struct node* prev = NULL;
if (temp != NULL && strcmp(temp->name, name) == 0) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && strcmp(temp->name, name) != 0) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
free(temp);
}
void printlist(struct node* head) {
struct node* temp = head;
while (temp != NULL) {
printf("%s %d\n", temp->name, temp->age);
temp = temp->next;
}
}
void freelist(struct node** head) {
struct node* temp;
while (*head != NULL) {
temp = *head;
*head = (*head)->next;
free(temp);
}
*head = NULL;
}
int main() {
struct node* head = NULL;
addstudent(&head, "张三", 20);
addstudent(&head, "李四", 21);
addstudent(&head, "王五", 22);
printf("初始链表信息:\n");
printlist(head);
updatestudent(head, "李四", "赵六", 23);
printf("\n修改后链表信息:\n");
printlist(head);
deletestudent(&head, "王五");
printf("\n删除后链表信息:\n");
printlist(head);
freelist(&head);
return 0;
}