Reverse each word in a linked list node

Given a linked list of strings, we need to reverse each word of the string in the given linked list.

Examples:

Input: geeksforgeeks a computer science portal for geeks 
Output: skeegrofskeeg a retupmoc ecneics latrop rof skeeg

Input: Publish your own articles on geeksforgeeks
Output: hsilbuP ruoy nwo selcitra no skeegrofskeeg 


Using a loop iterate the list till null and take string from each node and reverse the string.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to reverse each word
// in a linked list
#include <bits/stdc++.h>
using namespace std;
  
// Linked list Node structure
struct Node {
    string c;
    struct Node* next;
};
  
// Function to create newNode
// in a linked list
struct Node* newNode(string c)
{
    Node* temp = new Node;
    temp->c = c;
    temp->next = NULL;
    return temp;
};
  
// reverse each node data
void reverse_word(string& str)
{
    reverse(str.begin(), str.end());
}
  
void reverse(struct Node* head)
{
    struct Node* ptr = head;
  
    // iterate each node and call reverse_word
    // for each node data
    while (ptr != NULL) {
        reverse_word(ptr->c);
        ptr = ptr->next;
    }
}
  
// printing linked list
void printList(struct Node* head)
{
    while (head != NULL) {
        cout << head->c << " ";
        head = head->next;
    }
}
  
// Driver program
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: \n";
    printList(head);
  
    reverse(head);
  
    cout << "\n\nList after reverse: \n";
    printList(head);
  
    return 0;
}

chevron_right


Output:

List before reverse: 
Geeksforgeeks a computer science portal for geeks 

List after reverse: 
skeegrofskeeG a retupmoc ecneics latrop rof skeeg


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.