1.2k views
3 votes
IN C LANGUAGE

As part of the operation to remove a node from a list, it is essential to keep track of the node (or element) in the list.

User Shine J
by
8.3k points

1 Answer

2 votes

In C language, you can keep track of a node or element in a list by using a pointer variable. Here's an example:

```c

#include <stdio.h>

#include <stdlib.h>

// Node structure

struct Node {

int data;

struct Node* next;

};

// Function to remove a node from the list

void removeNode(struct Node** head, int value) {

struct Node* current = *head;

struct Node* prev = NULL;

// Traverse the list to find the node

while (current != NULL && current->data != value) {

prev = current;

current = current->next;

}

// If the node is found

if (current != NULL) {

// If the node is the head node

if (prev == NULL) {

*head = current->next;

} else {

prev->next = current->next;

}

free(current);

printf("Node with value %d is removed from the list.\\", value);

} else {

printf("Node with value %d not found in the list.\\", value);

}

}

// Function to print the list

void printList(struct Node* head) {

struct Node* current = head;

printf("List: ");

while (current != NULL) {

printf("%d ", current->data);

current = current->next;

}

printf("\\");

}

int main() {

// Create a sample list

struct Node* head = NULL;

struct Node* second = NULL;

struct Node* third = NULL;

head = (struct Node*)malloc(sizeof(struct Node));

second = (struct Node*)malloc(sizeof(struct Node));

third = (struct Node*)malloc(sizeof(struct Node));

head->data = 1;

head->next = second;

second->data = 2;

second->next = third;

third->data = 3;

third->next = NULL;

// Print the initial list

printf("Initial ");

printList(head);

// Remove a node from the list

removeNode(&head, 2);

// Print the updated list

printf("Updated ");

printList(head);

return 0;

}

```

In this code, we define a `Node` structure that represents a node in the list. Each node contains a `data` field and a `next` pointer that points to the next node in the list.

The `removeNode` function takes a double pointer to the head of the list and a value as input. It traverses the list to find the node with the given value. If the node is found, it adjusts the pointers to remove the node from the list and frees the memory. If the node is not found, it prints a message indicating that the node was not found.

The `printList` function simply traverses the list and prints the data values of each node.

In the `main` function, we create a sample list with three nodes and call the `removeNode` function to remove a node with a specific value. Finally, we print the updated list.

You can run this code to see the removal of a node from the list and observe the updated list.

User Tsroten
by
7.9k points

No related questions found