Reverse each word in a linked list node | C ++ program to reverse each word in a linked list ; Linked list Node structure ; Function to create newNode in a linked list ; reverse each node data ; iterate each node and call reverse_word for each node data ; printing linked list ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { string c ; struct Node * next ; } ; struct Node * newNode ( string c ) { Node * temp = new Node ; temp -> c = c ; temp -> next = NULL ; return temp ; } ; void reverse_word ( string & str ) { reverse ( str . begin ( ) , str . end ( ) ) ; } void reverse ( struct Node * head ) { struct Node * ptr = head ; while ( ptr != NULL ) { reverse_word ( ptr -> c ) ; ptr = ptr -> next ; } } void printList ( struct Node * head ) { while ( head != NULL ) { cout << head -> c << " ▁ " ; head = head -> next ; } } int main ( ) { Node * head = newNode ( " Geeksforgeeks " ) ; head -> next = newNode ( " a " ) ; head -> next -> next = newNode ( " computer " ) ; head -> next -> next -> next = newNode ( " science " ) ; head -> next -> next -> next -> next = newNode ( " portal " ) ; head -> next -> next -> next -> next -> next = newNode ( " for " ) ; head -> next -> next -> next -> next -> next -> next = newNode ( " geeks " ) ; cout << " List ▁ before ▁ reverse : ▁ STRNEWLINE " ; printList ( head ) ; reverse ( head ) ; cout << " List after reverse : " ; printList ( head ) ; return 0 ; }