qfedu-c-level/day11/d6.c

114 lines
2.1 KiB
C
Raw Normal View History

// 设计列表数据结构操作函数,包含创建空列表,列表添加、删除和修改等操作
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memset
// 定义链表节点
typedef struct node
{
char name[32];
struct node *next;
} Node;
// 创建空链表
Node *create_list()
{
Node *head = (Node *)malloc(sizeof(Node));
if (NULL == head)
{
perror("malloc error");
return NULL;
}
memset(head, 0, sizeof(Node));
return head;
}
// 添加节点
void add_node(Node *head, char *name)
{
Node *p = head;
while (p->next != NULL)
p = p->next;
Node *new_node = (Node *)malloc(sizeof(Node));
if (NULL == new_node)
{
perror("malloc error");
return;
}
memset(new_node, 0, sizeof(Node));
strcpy(new_node->name, name);
p->next = new_node;
}
// 打印链表
void print_list(Node *head)
{
Node *p = head->next;
while (p != NULL)
{
printf("%s ", p->name);
p = p->next;
}
printf("\n");
}
// 删除节点
void delete_node(Node *head, char *name)
{
Node *p = head;
while (p->next != NULL)
{
if (strcmp(p->next->name, name) == 0)
{
Node *temp = p->next;
p->next = p->next->next;
free(temp);
return;
}
p = p->next;
}
}
// 修改节点
void modify_node(Node *head, char *name, char *new_name)
{
Node *p = head->next;
while (p != NULL)
{
if (strcmp(p->name, name) == 0)
{
strcpy(p->name, new_name);
return;
}
p = p->next;
}
}
// 释放链表
void free_list(Node *head)
{
Node *p = head;
while (p != NULL)
{
Node *temp = p;
p = p->next;
free(temp);
}
}
int main()
{
Node *head = create_list();
add_node(head, "a");
add_node(head, "b");
add_node(head, "c");
add_node(head, "d");
print_list(head);
delete_node(head, "b");
print_list(head);
modify_node(head, "c", "e");
print_list(head);
free_list(head);
return 0;
}