要删除双向链表中的某个节点,需要执行以下步骤:
以下是一个示例代码实现:
#include <stdio.h>
#include <stdlib.h>
// 双向链表节点结构体
typedef struct Node {
int data;
struct Node *prev; // 指向前一个节点的指针
struct Node *next; // 指向后一个节点的指针
} Node;
// 删除节点函数
void deleteNode(Node **head, int value) {
if (*head == NULL) {
printf("链表为空,无法删除节点\n");
return;
}
Node *current = *head;
while (current != NULL) {
if (current->data == value) {
if (current == *head) {
// 要删除的节点是头节点
*head = current->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(current);
} else if (current->next == NULL) {
// 要删除的节点是尾节点
current->prev->next = NULL;
free(current);
} else {
// 要删除的节点是中间节点
current->prev->next = current->next;
current->next->prev = current->prev;
free(current);
}
printf("成功删除节点\n");
return;
}
current = current->next;
}
printf("未找到要删除的节点\n");
}
// 打印链表函数
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL; // 链表头指针
// 创建链表
Node *node1 = (Node *)malloc(sizeof(Node));
node1->data = 1;
node1->prev = NULL;
node1->next = NULL;
head = node1;
Node *node2 = (Node *)malloc(sizeof(Node));
node2->data = 2;
node2->prev = node1;
node2->next = NULL;
node1->next = node2;
Node *node3 = (Node *)malloc(sizeof(Node));
node3->data = 3;
node3->prev = node2;
node3->next = NULL;
node2->next = node3;
// 打印原始链表
printf("原始链表:");
printList(head);
// 删除节点
deleteNode(&head, 2);
// 打印删除节点后的链表
printf("删除节点后的链表:");
printList(head);
return 0;
}
此示例中,首先创建了一个包含三个节点的双向链表。然后调用deleteNode
函数删除值为2的节点。最后打印删除节点后的链表。