0% found this document useful (0 votes)
2 views2 pages

Linked List Search and Insert in C

The document contains C code for a linked list implementation with functions to insert nodes, search for a target value using a comparison function, and free the list's memory. It includes a main function that demonstrates inserting integers into the list and searching for both present and absent integers. The code also defines a structure for the nodes and handles dynamic memory allocation.

Uploaded by

Abhishek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Linked List Search and Insert in C

The document contains C code for a linked list implementation with functions to insert nodes, search for a target value using a comparison function, and free the list's memory. It includes a main function that demonstrates inserting integers into the list and searching for both present and absent integers. The code also defines a structure for the nodes and handles dynamic memory allocation.

Uploaded by

Abhishek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>
#include <stdlib.h>

typedef struct Node {


void *data;
struct Node *next;
} Node;

int search(Node* head, void* target, int (*cmp_fn)(void*, void*)) {


Node* current = head;
while (current != NULL) {
if (cmp_fn(current->data, target) == 0) {
return 1;
}
current = current->next;
}
return 0;
}

int compare_ints(void* a, void* b) {


return (*(int*)a - *(int*)b);
}

Node* insert(Node* head, void* new_data, size_t data_size) {


Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = malloc(data_size);
memcpy(new_node->data, new_data, data_size);
new_node->next = head;
return new_node;
}

void free_list(Node* head) {


Node* current = head;
Node* next_node;

while (current != NULL) {


next_node = current->next;
free(current->data);
free(current);
current = next_node;
}
}

void main() {
Node* int_list = NULL;

int nums[] = {10, 20, 30, 40, 50};


for (int i = 0; i < 5; i++) {
int_list = insert(int_list, &nums[i], sizeof(int));
}

// Test search for an integer in the list


int target = 30;
if (search(int_list, &target, compare_ints)) {
printf("Found %d in the list\n", target);
} else {
printf("Did not find %d in the list\n", target);
}
// Test search for an integer not in the list
int target2 = 60;
if (search(int_list, &target2, compare_ints)) {
printf("Found %d in the list\n", target2);
} else {
printf("Did not find %d in the list\n", target2);
}

// Free the linked list memory


free_list(int_list);
}

You might also like