顺序查找算法c语言链表
时间: 2024-09-06 08:00:56 浏览: 24
顺序查找算法是一种基础的搜索算法,它按照数据结构的线性顺序,逐个检查每个元素直到找到所需的特定值或者遍历完所有的元素。在链表中实现顺序查找,需要从头节点开始,逐个访问链表中的节点,直到找到目标值或遍历完整个链表。
以下是使用C语言在链表中实现顺序查找的一个简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
exit(-1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 顺序查找算法实现
Node* sequentialSearch(Node* head, int target) {
Node* current = head;
while (current != NULL) {
if (current->data == target) {
return current; // 找到目标值,返回当前节点
}
current = current->next; // 移动到下一个节点
}
return NULL; // 未找到目标值,返回NULL
}
int main() {
// 创建链表并初始化
Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
// 查找链表中的值
int target = 3;
Node* foundNode = sequentialSearch(head, target);
if (foundNode != NULL) {
printf("找到元素:%d\n", foundNode->data);
} else {
printf("链表中没有找到元素:%d\n", target);
}
// 释放链表内存...
return 0;
}
```
在这个示例中,我们首先定义了一个链表节点的结构体`Node`,然后实现了创建新节点的函数`createNode`。顺序查找函数`sequentialSearch`接受链表头节点和要查找的目标值,然后遍历链表,如果找到目标值,则返回对应的节点指针,否则返回`NULL`。