Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Reverse a Linked List
Next article icon

Reverse each word in a linked list node

Last Updated : 04 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Implementation:

C++
// 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; } 
Java
// Java program to reverse each word  // in a linked list  class GFG {  // Linked list Node ure  static class Node {      String c;      Node next;  };   // Function to create newNode  // in a linked list  static Node newNode(String c)  {      Node temp = new Node();      temp.c = c;      temp.next = null;      return temp;  };   // reverse each node data  static String reverse_word(String str)  {      String s = "";     for(int i = 0; i < str.length(); i++)     s = str.charAt(i) + s;     return s; }   static Node reverse( Node head)  {      Node ptr = head;       // iterate each node and call reverse_word      // for each node data      while (ptr != null)     {          ptr.c = reverse_word(ptr.c);          ptr = ptr.next;      }      return head; }   // printing linked list  static void printList( Node head)  {      while (head != null)     {          System.out.print( head.c + " ");          head = head.next;      }  }   // Driver program  public static void main(String args[]) {      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");       System.out.print( "List before reverse: \n");      printList(head);       head = reverse(head);       System.out.print( "\n\nList after reverse: \n");      printList(head);   }  }  // This code is contributed by Arnab Kundu 
Python3
# Python3 program to reverse each word  # in a linked list   # Node of a linked list  class Node:      def __init__(self, next = None, data = None):          self.next = next         self.data = data   # Function to create newNode  # in a linked list  def newNode(c) :      temp = Node()      temp.c = c      temp.next = None     return temp   # reverse each node data  def reverse_word(str) :     s = ""     i = 0     while(i < len(str) ):         s = str[i] + s         i = i + 1     return s  def reverse( head) :     ptr = head       # iterate each node and call reverse_word      # for each node data      while (ptr != None):         ptr.c = reverse_word(ptr.c)          ptr = ptr.next          return head  # printing linked list  def printList( head) :      while (head != None):         print( head.c ,end = " ")          head = head.next      # Driver program  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")   print( "List before reverse: ")  printList(head)   head = reverse(head)   print( "\n\nList after reverse: ")  printList(head)   # This code is contributed by Arnab Kundu 
C#
// C# program to reverse each word  // in a linked list using System;  class GFG  {           // Linked list Node ure      public class Node      {          public String c;          public Node next;      };           // Function to create newNode      // in a linked list      static Node newNode(String c)      {          Node temp = new Node();          temp.c = c;          temp.next = null;          return temp;      }           // reverse each node data      static String reverse_word(String str)      {          String s = "";          for(int i = 0; i < str.Length; i++)              s = str[i] + s;          return s;      }           static Node reverse( Node head)      {          Node ptr = head;               // iterate each node and call reverse_word          // for each node data          while (ptr != null)          {              ptr.c = reverse_word(ptr.c);              ptr = ptr.next;          }          return head;      }           // printing linked list      static void printList( Node head)      {          while (head != null)          {              Console.Write( head.c + " ");              head = head.next;          }      }           // Driver program      public static void Main(String []args)      {          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");               Console.Write( "List before reverse: \n");          printList(head);               head = reverse(head);               Console.Write( "\n\nList after reverse: \n");          printList(head);           }  }   // This code contributed by Rajput-Ji 
JavaScript
<script>  // JavaScript program to reverse each word  // in a linked list  // Linked list Node ure  class Node  {      constructor()     {         this.c = "";         this.next = null;     } };   // Function to create newNode  // in a linked list  function newNode(c)  {      var temp = new Node();      temp.c = c;      temp.next = null;      return temp;  }   // reverse each node data  function reverse_word(str)  {      var s = "";      for(var i = 0; i < str.length; i++)          s = str[i] + s;      return s;  }   function reverse(head)  {      var ptr = head;       // iterate each node and call reverse_word      // for each node data      while (ptr != null)      {          ptr.c = reverse_word(ptr.c);          ptr = ptr.next;      }      return head;  }   // printing linked list  function printList( head)  {      while (head != null)      {          document.write( head.c + " ");          head = head.next;      }  }   // Driver program  var 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");  document.write( "List before reverse: <br>");  printList(head);  head = reverse(head);  document.write( "<br><br>List after reverse: <br>");  printList(head);   </script>  

Output: 
List before reverse:  Geeksforgeeks a computer science portal for geeks   List after reverse:  skeegrofskeeG a retupmoc ecneics latrop rof skeeg

 

Time complexity : O(n) 
Auxiliary Space : O(1)


Next Article
Reverse a Linked List

S

Shahnawaz_Ali
Improve
Article Tags :
  • Misc
  • Strings
  • Linked List
  • DSA
Practice Tags :
  • Linked List
  • Misc
  • Strings

Similar Reads

  • Reverse alternate K nodes in a Singly Linked List
    Given a linked list, The task is to reverse alternate k nodes. If the number of nodes left at the end of the list is fewer than k, reverse these remaining nodes or leave them in their original order, depending on the alternation pattern. Example: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -
    15+ min read
  • Can we reverse a linked list in less than O(n)?
    It is not possible to reverse a simple singly linked list in less than O(n). A simple singly linked list can only be reversed in O(n) time using recursive and iterative methods. A doubly linked list with head and tail pointers while only requiring swapping the head and tail pointers which require le
    1 min read
  • XOR linked list: Reverse last K nodes of a Linked List
    Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1, K = 3Output: 7<–>6<–>8<–>1<–>3<–>11 Input: LL: 7 <–> 6 <
    14 min read
  • C Program to reverse each node value in Singly Linked List
    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
    2 min read
  • Reverse a Linked List
    Given a linked list, the task is to reverse the linked list by changing the links between nodes. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> NULLOutput: head: 4 -> 3 -> 2 -> 1 -> NULLExplanation: Reversed Linked List: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOu
    15+ min read
  • Reverse a circular linked list
    Given a circular linked list of size n. The problem is to reverse the given circular linked list by changing links between the nodes.Examples: INPUT: OUTPUT: Approach: The approach is same as followed in reversing a singly linked list. Only here we have to make one more adjustment by linking the las
    7 min read
  • Reverse each word in a sentence in Python
    In this article, we will explore various methods to reverse each word in a sentence. The simplest approach is by using a loop. Using LoopsWe can simply use a loop (for loop) to reverse each word in a sentence. [GFGTABS] Python s = "Hello World" # Split 's' into words words = s.spli
    2 min read
  • Reverse a Linked List in groups of given size
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
    3 min read
  • Reverse all the word in a String represented as a Linked List
    Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-
    15 min read
  • Reverse a sublist of linked list
    Given a linked list and positions m and n. We need to reverse the linked list from position m to n. Examples: Input : linkedlist : 10->20->30->40->50->60->70->NULL , m = 3 and n = 6Output : 10->20->60->50->40->30->70->NULLExplanation: Linkedlist reversed sta
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences