要刪除雙向鏈表中的某個節點,需要執行以下步驟:
以下是一個示例代碼實現:
#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的節點。最后打印刪除節點后的鏈表。