在C語言雙向鏈表中查找元素的步驟如下:
下面是一個簡單的示例代碼,演示如何在雙向鏈表中查找元素:
#include <stdio.h>
#include <stdlib.h>
// 定義雙向鏈表節點結構體
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// 在雙向鏈表中查找元素
struct Node* search(struct Node* head, int target) {
struct Node* current = head;
// 遍歷整個鏈表
while (current != NULL) {
// 檢查當前節點的值是否等于目標元素
if (current->data == target) {
return current; // 找到目標元素,返回當前節點
}
current = current->next; // 繼續遍歷下一個節點
}
return NULL; // 遍歷完整個鏈表都沒有找到目標元素
}
int main() {
// 創建雙向鏈表
struct Node* head = NULL;
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 10;
node1->prev = NULL;
node1->next = node2;
node2->data = 20;
node2->prev = node1;
node2->next = node3;
node3->data = 30;
node3->prev = node2;
node3->next = NULL;
head = node1; // 頭節點為node1
// 在鏈表中查找元素
int target = 20;
struct Node* result = search(head, target);
if (result != NULL) {
printf("Element %d found in the list.\n", target);
} else {
printf("Element %d not found in the list.\n", target);
}
// 釋放內存
free(node1);
free(node2);
free(node3);
return 0;
}
在上面的示例代碼中,首先創建了一個包含3個節點的雙向鏈表,然后通過調用search函數在鏈表中查找元素20。最后根據查找結果輸出相應的提示信息。