温馨提示×

c语言如何实现单链表的查找

小亿
89
2024-10-11 16:41:16
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,实现单链表查找的方法是遍历链表,逐个检查节点的值,直到找到目标值或到达链表末尾。以下是一个简单的示例:

首先,定义链表节点结构体:

typedef struct Node {
    int data;
    struct Node* next;
} Node;

然后,创建一个链表并插入一些节点:

#include <stdio.h>
#include <stdlib.h>

// 插入节点到链表头部
void insertAtHead(Node** head, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = *head;
    *head = newNode;
}

int main() {
    Node* head = NULL;

    insertAtHead(&head, 3);
    insertAtHead(&head, 2);
    insertAtHead(&head, 1);

    return 0;
}

接下来,实现链表查找功能:

// 查找链表中的目标值
Node* searchList(Node* head, int target) {
    Node* current = head;

    while (current != NULL) {
        if (current->data == target) {
            return current;
        }
        current = current->next;
    }

    return NULL; // 如果未找到目标值,返回NULL
}

最后,在main函数中调用searchList函数查找链表中的目标值:

int main() {
    Node* head = NULL;

    insertAtHead(&head, 3);
    insertAtHead(&head, 2);
    insertAtHead(&head, 1);

    Node* result = searchList(head, 2);
    if (result != NULL) {
        printf("找到目标值: %d\n", result->data);
    } else {
        printf("未找到目标值\n");
    }

    return 0;
}

这个示例中,链表包含3个节点,值分别为1、2和3。调用searchList函数查找值为2的节点,将返回该节点。如果查找失败,函数将返回NULL。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c语言怎么实现单链表反转

0