Untitled
unknown
c_cpp
2 years ago
3.0 kB
2
Indexable
/* explain me how to use linked lists in c A linked list is a data structure that consists of a group of nodes which together represent a sequence. In a linked list, each node contains a data field and a reference (link) to the next node in the sequence. This allows for efficient insertion or removal of elements from any position in the sequence. Here is an example of how to use linked lists in C: */ #include <stdio.h> #include <stdlib.h> // define a structure for the linked list node struct node { int data; struct node *next; }; // function to create a new node with the given data struct node *new_node(int data) { // allocate memory for the new node struct node *new_node = malloc(sizeof(struct node)); // set the data and next fields of the new node new_node->data = data; new_node->next = NULL; return new_node; } // function to insert a new node at the beginning of the linked list void insert_at_beginning(struct node **head, int data) { // create a new node with the given data struct node *new_node = new_node(data); // set the next field of the new node to point to the current head of the list new_node->next = *head; // update the head of the linked list to point to the new node *head = new_node; } // function to insert a new node at the end of the linked list void insert_at_end(struct node **head, int data) { // create a new node with the given data struct node *new_node = new_node(data); // if the linked list is empty, set the head of the list to point to the new node if (*head == NULL) { *head = new_node; } else { // find the last node in the linked list struct node *current = *head; while (current->next != NULL) { current = current->next; } // set the next field of the last node to point to the new node current->next = new_node; } } // function to remove the first node from the linked list void remove_first(struct node **head) { // if the linked list is empty, return if (*head == NULL) { return; } // save a pointer to the current head of the list struct node *current = *head; // update the head of the linked list to point to the second node *head = current->next; // free the memory occupied by the current head free(current); } // function to print the elements of the linked list void print_list(struct node *head) { // traverse the linked list and print the data of each node struct node *current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } int main() { // create an empty linked list struct node *head = NULL; // insert some elements at the beginning of the list insert_at_beginning(&head, 1); insert_at_beginning(&head, 2); insert_at_beginning(&head, 3); // print the linked list print_
Editor is loading...