Mr

mail@pastecode.io avatar
unknown
csharp
7 months ago
2.5 kB
1
Indexable
Never
// Define a node structure
struct node {
  int data; // The data stored in the node
  struct node *next; // The pointer to the next node
};

// Create a new node with a given data value
struct node *create_node(int data) {
  struct node *new_node = malloc(sizeof(struct node)); // Allocate memory for the node
  if (new_node == NULL) { // Check if the allocation was successful
    printf("Error: could not allocate memory for the node.\n");
    exit(1); // Terminate the program
  }
  new_node->data = data; // Set the data value
  new_node->next = NULL; // Set the next pointer to NULL
  return new_node; // Return the new node
}

// Add a node to the front of the list
void add_node(struct node **head, int data) {
  struct node *new_node = create_node(data); // Create a new node
  new_node->next = *head; // Set the next pointer of the new node to the current head
  *head = new_node; // Set the head pointer to the new node
}

// Delete a node with a given data value from the list
void delete_node(struct node **head, int data) {
  struct node *current = *head; // Start from the head of the list
  struct node *previous = NULL; // Keep track of the previous node
  while (current != NULL) { // Loop until the end of the list
    if (current->data == data) { // If the current node has the data value to be deleted
      if (previous == NULL) { // If the current node is the head of the list
        *head = current->next; // Set the head pointer to the next node
      } else { // If the current node is not the head of the list
        previous->next = current->next; // Set the previous node's next pointer to the current node's next pointer
      }
      free(current); // Free the memory of the current node
      return; // Return from the function
    }
    previous = current; // Update the previous node
    current = current->next; // Move to the next node
  }
  printf("Error: could not find the node with data %d.\n", data); // If the loop ends without finding the node, print an error message
}

// Find a node with a given data value in the list
struct node *find_node(struct node *head, int data) {
  struct node *current = head; // Start from the head of the list
  while (current != NULL) { // Loop until the end of the list
    if (current->data == data) { // If the current node has the data value to be searched
      return current; // Return the current node
    }
    current = current->next; // Move to the next node
  }
  return NULL; // If the loop ends without finding the node, return NULL
}
Leave a Comment