Can you create a linked list structure in C that uses a insert, delete, add and search…
- User
Can you create a linked list structure in C that uses a insert, delete, add and search function?
Assistant
Yes, I can help you create a linked list structure in C that uses insert, delete, add, and search functions. Here is an example implementation:
#include <stdio.h> #include <stdlib.h> // Structure to represent a node in the linked list struct Node { int data; // Data stored in the node struct Node *next; // Pointer to the next node in the list }; // Function to create a new node and insert it into the list struct Node *insert(struct Node *head, int data) { struct Node *new_node = malloc(sizeof(struct Node)); new_node->data = data; new_node->next = head; head = new_node; return new_node; } // Function to delete a node from the list void delete(struct Node *head, int data) { struct Node *current = head; while (current != NULL && current->data != data) { current = current->next; } if (current != NULL) { current->next = NULL; free(current); } } // Function to add a node at the beginning of the list void add(struct Node *head, int data) { struct Node *new_node = malloc(sizeof(struct Node)); new_node->data = data; new_node->next = head; head = new_node; } // Function to search for a node in the list int search(struct Node *head, int data) { struct Node *current = head; while (current != NULL && current->data != data) { current = current->next; } return current != NULL ? 1 : 0; } int main() { struct Node *head = NULL; // Insert some nodes into the list head = insert(head, 1); head = insert(head, 2); head = insert(head, 3); head = insert(head, 4); // Delete a node from the list delete(head, 2); // Add a node to the beginning of the list add(head, 5); // Search for a node in the list printf("%d\n", search(head, 3)); // Output: 1 return 0; }Here's an explanation of each function:
insert: Creates a new node with the givendatavalue and inserts it into the list. It returns the new node.delete: Deletes the node with the givendatavalue from the list. It returnsNULLif the node is not found.add: Adds a new node to the beginning of the list with the givendatavalue.search: Searches for the node with the givendatavalue in the list. It returns1if the node is found and0otherwise.
In the
mainfunction, we create an empty listheadand perform various operations on it, including inserting, deleting, adding, and searching nodes.Note that this implementation uses dynamic memory allocation, so you'll need to include the
stdlib.hheader file and usemalloc()to allocate memory for the nodes. Also, this implementation assumes that the nodes are stored in a singly linked list, where each node points to the next node in the list.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.