Updating Linked List or Modifying a Linked List | Operation of LL

10 min read

Updating Linked List or modifying Linked List means replacing the data of a particular node with the new data.  Let us now look at a program to perform this operation.

 

C program to update an element in a linked list

#include <stdio.h>
#include <stdlib.h>

// Creating node with data and a pointer

struct node {
int data;
struct node *next;
}*head;
void createList(int n);
void update_element(int data);
void displayList();

int main()
{
int n, data, element;
printf("\nEnter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nThe List is \n");
displayList();
printf("\nEnter the element to be updated in the list : "); // value of the element to be searched in the list
scanf("%d",&element);
update_element(element);
displayList();
return 0;
}

void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
// When the list is empty
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
printf("\nEnter the data of node 1: ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("\nEnter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}}}}

void update_element(int data)
{
int count = 0;
int update_ele;
struct node* temp;
temp = head;
while(temp != NULL) // Start traversing from head node
{
if(temp -> data == data)
{
printf("\nEnter the new data to update the old data : ");
scanf("%d",&update_ele);
temp -> data = update_ele; // change the element in the list
}
else
{
count = count + 1;
temp = temp -> next;
}}}

void displayList()
{
struct node *temp;
if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
while(temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}}


OUTPUT

updating linked list with the given element

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error