c语言的双向循环链表的增删改查代码
时间: 2024-05-22 18:15:09 浏览: 111
我可以为您提供 C 语言双向循环链表的增删改查代码示例,如下所示:
// 定义双向链表节点结构体
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
// 初始化双向链表
void init_list(Node **head) {
*head = (Node *) malloc(sizeof(Node));
(*head)->prev = *head;
(*head)->next = *head;
(*head)->data = 0; // 头结点不存储数据
}
// 插入节点(在第 index 个节点后插入)
void insert_node(Node *head, int index, int data) {
Node *p, *newNode;
p = head;
for (int i = 0; i < index && p != head->prev; i++, p = p->next);
if (p == head->prev && index != 0) {
printf("Index out of range!\n");
return;
}
newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->prev = p;
newNode->next = p->next;
p->next->prev = newNode;
p->next = newNode;
}
// 删除节点(删除第 index 个节点)
void delete_node(Node *head, int index) {
Node *p;
p = head;
for (int i = 0; i < index && p->next != head; i++, p = p->next);
if (p->next == head && index != 0) {
printf("Index out of range!\n");
return;
}
p->prev->next = p->next;
p->next->prev = p->prev;
free(p);
}
// 修改节点数据(将第 index 个节点的数据修改为 data)
void modify_node(Node *head, int index, int data) {
Node *p;
p = head->next;
for (int i = 0; i < index; i++, p = p->next) {
if (p == head) {
printf("Index out of range!\n");
return;
}
}
p->data = data;
}
// 查找节点数据(查找第 index 个节点的数据)
int search_node(Node *head, int index) {
Node *p;
p = head->next;
for (int i = 0; i < index; i++, p = p->next) {
if (p == head) {
printf("Index out of range!\n");
return -1;
}
}
return p->data;
}
请注意,此代码仅是示例,实际使用时还需要考虑链表为空或索引超出链表长度的异常情况。
阅读全文