要刪除雙向鏈表中的某個節(jié)點,需要執(zhí)行以下步驟:
以下是一個示例代碼實現(xiàn):
#include <stdio.h>
#include <stdlib.h>
// 雙向鏈表節(jié)點結(jié)構(gòu)體
typedef struct Node {
int data;
struct Node *prev; // 指向前一個節(jié)點的指針
struct Node *next; // 指向后一個節(jié)點的指針
} Node;
// 刪除節(jié)點函數(shù)
void deleteNode(Node **head, int value) {
if (*head == NULL) {
printf("鏈表為空,無法刪除節(jié)點\n");
return;
}
Node *current = *head;
while (current != NULL) {
if (current->data == value) {
if (current == *head) {
// 要刪除的節(jié)點是頭節(jié)點
*head = current->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(current);
} else if (current->next == NULL) {
// 要刪除的節(jié)點是尾節(jié)點
current->prev->next = NULL;
free(current);
} else {
// 要刪除的節(jié)點是中間節(jié)點
current->prev->next = current->next;
current->next->prev = current->prev;
free(current);
}
printf("成功刪除節(jié)點\n");
return;
}
current = current->next;
}
printf("未找到要刪除的節(jié)點\n");
}
// 打印鏈表函數(shù)
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL; // 鏈表頭指針
// 創(chuàng)建鏈表
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);
// 刪除節(jié)點
deleteNode(&head, 2);
// 打印刪除節(jié)點后的鏈表
printf("刪除節(jié)點后的鏈表:");
printList(head);
return 0;
}
此示例中,首先創(chuàng)建了一個包含三個節(jié)點的雙向鏈表。然后調(diào)用deleteNode
函數(shù)刪除值為2的節(jié)點。最后打印刪除節(jié)點后的鏈表。