C Program to reverse each node value in Singly Linked List

CServer Side ProgrammingProgramming

In this article, we are given a linked list. Our task is to create a C program to reverse each node value in singly linked list.

We will take each node of the linked list and reverse the value.

Linked list is a sequence of links that contains items that are linked to another link.

Let’s take an example to understand the problem,

Input

34 12 89 56 72

Output

43 21 98 65 27

To solve this problem, we will traverse the singly linked list and take each node. And then reverse the value of the current node.

Program to reverse each node value in Singly Linked List

// Program to reverse each node value in Singly Linked List.

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
struct Node {
   int data;
   struct Node* next;
};
struct Node* insertNode(int key) {
   struct Node* temp = new Node;
   temp->data = key;
   temp->next = NULL;
   return temp;
}
int reverseValue(int number) {
   int revElement = 0, rem;
   while (number != 0) {
      rem = number % 10;
      revElement = revElement * 10 + rem;
      number = number / 10;
   }
   return revElement;
}
void reverseLinkedListElements(struct Node* node) {
   if (node == NULL)
      return;
   while (node != NULL) {
      node->data = reverseValue(node->data);
      node = node->next;
   }
}
void printLinkedList(struct Node* node) {
   while (node != NULL) {
      printf("%d ", node->data);
      node = node->next;
   }
}
int main() {
   struct Node* head = NULL;
   head = insertNode(34);
   head->next = insertNode(12);
   head->next->next = insertNode(89);
   head->next->next->next = insertNode(56);
   head->next->next->next->next = insertNode(72);
   printf("Orignal Linked List :\t");
   printLinkedList(head);
   reverseLinkedListElements(head);
   printf("\nAltered Linked List:\t");
   printLinkedList(head);
   return 0;
}

Output

Orignal Linked List : 34 12 89 56 72
Altered Linked List: 43 21 98 65 27
raja
Published on 18-Jul-2020 06:06:54
Advertisements