C Program to reverse each node value in Singly Linked List
Last Updated :
15 Sep, 2022
A linked list is a linear collection of data elements, in which each node points to the next node. Unlike an array, it doesn’t have upper limit and hence extremely useful. The task is to access value of each node of linked list and reverse them.
Examples:
Input : 56 87 12 49 35
Output : 65 78 21 94 53
Input : 128 87 12433 491 33
Output : 821 78 33421 194 33
Algorithm: The task can be accomplished as:
- Linearly traverse each node of the singly linked list.
- Reverse the value of each node.
- Store the reversed value in the current node.
Implementation:
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* newNode( int key)
{
struct Node* temp
= ( struct Node*) malloc ( sizeof ( struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
int reverse( int number)
{
int new_num = 0, rem;
while (number != 0) {
rem = number % 10;
new_num = new_num * 10 + rem;
number = number / 10;
}
return new_num;
}
void reverseIndividualData( struct Node* node)
{
if (node == NULL)
return ;
while (node != NULL) {
node->data = reverse(node->data);
node = node->next;
}
}
void printList( struct Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
int main()
{
struct Node* head = NULL;
head = newNode(56);
head->next = newNode(87);
head->next->next = newNode(12);
head->next->next->next = newNode(49);
head->next->next->next->next = newNode(35);
printf (
"\nList before reversing individual data item \n" );
printList(head);
reverseIndividualData(head);
printf ( "\nList after reversing individual data item\n" );
printList(head);
return 0;
}
|
Output
List before reversing individual data item
56 87 12 49 35
List after reversing individual data item
65 78 21 94 53
Share your thoughts in the comments
Please Login to comment...