单链表查找的C语言代码?
时间: 2023-05-13 09:07:42 浏览: 88
以下是单链表查找的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void search(struct Node* head, int key) {
struct Node* current = head;
int pos = 1;
while (current != NULL) {
if (current->data == key) {
printf("Key found at position %d\n", pos);
return;
}
current = current->next;
pos++;
}
printf("Key not found\n");
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
search(head, 2); // search for key 2 in the linked list
return 0;
}
```
阅读全文