Updating in Doubly Linked List | Updating an element in doubly linked list

10 min read

Updating elements is one of the common operations in a doubly linked list. The list is traversed from the beginning and checked if the given element is present in the list. If present, then that element is replaced with the given element. This is how updating in doubly linked list works.

 

C code for updating in Doubly Linked List

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

//structure of Node with prev and next pointers
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
void createList(int n);
void displayList();
void update_element(int data);

int main()
{
int n, data;
head = NULL;
last = NULL;
printf("\nEnter the total number of nodes in list : "); // Input the number of nodes
scanf("%d", &n);
createList(n);
printf("\n\nTHE DOUBLY LINKED LIST IS :\n\n");
displayList();
printf("\n\nEnter the element you want to replace : ");
scanf("%d",&data);
update_element(data);
printf("\n\nThe Doubly Linked list after Updating : \n\n");
displayList();
return 0;
}
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));
printf("\nEnter data of node 1 : ");
scanf("%d", &data);
head->data = data;
head->prev = NULL; // HEAD nodes's prev is set to NULL
head->next = NULL; // HEAD nodes's next is set to NULL
last = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("\nEnter data of node %d : ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;
last->next = newNode; // Link previous node with the new node
last = newNode; // Make new node as last node
}}}

void displayList()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("\nList is empty.\n");
}
else
{
temp = head;
while(temp != NULL)
{
printf("%d\t", temp->data);
n++;
/* Move the current pointer to next node */
temp = temp->next;
}}}
void update_element(int data)
{
int updated_data;
struct node * temp = (struct node *)malloc(sizeof(struct node));
temp = head;
int pos = 0;
while(temp != NULL)
{
if(temp -> data == data)
{
printf("\n\nEnter the new element : ");
scanf("%d",&updated_data);
temp -> data = updated_data;
}
else
{
temp = temp ->next;
pos++;
}}}

 

OUTPUT

Updating in Doubly Linked List

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