Reverse all the word in a String represented as a Linked List - GeeksforGeeks

23 Jun, 2021
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-> ->G->e->e->k->s-> ->f->o->r-> ->G->e->e->k->s 
Examples: 
Input: I love Geeks for Geeks Output: Geeks for Geeks love I
Input: practice makes a man perfect Output: perfect man a makes practice 
Approach: The idea is to navigate the linked list from the beginning. Every time space is encountered, swap the space to the beginning of that word. Repeat this step until the last node is reached. Finally set the first words last letter to point null which will become the last node and keep changing the pointers.
Below is the implementation of the approach:  
Java
C#
// Linked List Implementationpublic class Node {    public Node(char data, Node next)    {        Data = data;        Next = next;    }    public char Data;    public Node Next;}class GFG {     // Function to create a linked list    // from the given String    private static Node CreateLinkedList(String s)    {        Node header = null;        Node temp = null;        // Generates characters from the given string        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            Node node = new Node(c, null);             if (header == null) {                header = node;                temp = header;            }            else {                temp.Next = node;                temp = temp.Next;            }        }        return header;    }     // Function to reverse the words    // Assume str = "practice makes man perfect"    // to understand proper understanding of the code    private static Node Reverse(Node header)    {        if (header == null)            return header;         Node wordStartPosition = null;        Node endOfSentence = null;        Node sentenceStartPosition = null;         // Initialize wordStartPosition to header        // ie. node 'p' first letter of the word 'practice'        wordStartPosition = header;         // Navigate the linked list until        // a space(' ') is found or header is null        //(this is for handing if there is        // only one word in the given sentence)        while (header != null && header.Data != ' ') {             // Keep track the previous node.            // This will become the            // last node of the linked list            endOfSentence = header;             // Keep moving to the next node            header = header.Next;        }         // After the above while loop,        // endOfSentence points to        // the last letter 'e'of word 'practice'        // header points to the space(' ')        // which is next to word 'practice'         // If header is null then there is only        // one word in the given sentence        // so set header to the        // first/wordStartPosition node and return.        if (header == null) {            header = wordStartPosition;            return header;        }         do {             // Swapping the space ie.            // convert 'practice<space>' to            //'<space>practice'             // store the node which is next to space(' ')            // 'm' which is the first letter of the word 'make'            Node temp = header.Next;            header.Next = wordStartPosition;            wordStartPosition = header;            header = temp;             Node prev = null;            // Setting sentenceStartPosition to node 'm'            //(first letter of the word 'make')            sentenceStartPosition = header;             // Again Navigate the linked list until            // a space(' ') is found or            // header == null end of the linked list            while (header != null && header.Data != ' ') {                prev = header;                header = header.Next;            }             // When the next space is found,            // change the pointer to point the previous space            // ie. the word is being converted to            // "m->a->k->e->s-> ->p->r->a->c->t->i->c->e"            prev.Next = wordStartPosition;             // Newly found space will point to            //'m' first letter of the word 'make'            wordStartPosition = sentenceStartPosition;            if (header == null)                break;             // Repeat the loop until            // the end of the linked list is reached        } while (header != null);         header = sentenceStartPosition;         // Set the last node's next to null        // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null        endOfSentence.Next = null;        return header;    }     // Function to print the Linked List    private static void PrintList(Node Header)    {        Node temp = Header;        // Navigate till the end and print the data in each node        while (temp != null) {            System.out.print(temp.Data);            temp = temp.Next;        }    }     // Driver code    public static void main(String[] args)    {        String s = "practice makes a man perfect";         // Convert given string to a linked list        // with character as data in each node        Node header = CreateLinkedList(s);         System.out.println("Before:");        PrintList(header);         header = Reverse(header);         System.out.println("\nAfter:");        PrintList(header);    }}
using System; // Linked List Implementationpublic class Node{    public Node(char data, Node next)    {        Data = data;        Next = next;    }    public char Data;    public Node Next;} class GFG{     // Function to create a linked list    // from the given String    private static Node CreateList(String s)    {        Node header = null;        Node temp = null;                 // Generates characters from the given string        for (int i = 0; i < s.Length; i++)        {            char c = s[i];            Node node = new Node(c, null);             if (header == null)            {                header = node;                temp = header;            }            else            {                temp.Next = node;                temp = temp.Next;            }        }        return header;    }     // Function to reverse the words    // Assume str = "practice makes man perfect"    // to understand proper understanding of the code    private static Node Reverse(Node header)    {        if (header == null)            return header;         Node wordStartPosition = null;        Node endOfSentence = null;        Node sentenceStartPosition = null;         // Initialize wordStartPosition to header        // ie. node 'p' first letter of the word 'practice'        wordStartPosition = header;         // Navigate the linked list until        // a space(' ') is found or header is null        //(this is for handing if there is        // only one word in the given sentence)        while (header != null && header.Data != ' ')        {             // Keep track the previous node.            // This will become the            // last node of the linked list            endOfSentence = header;             // Keep moving to the next node            header = header.Next;        }         // After the above while loop,        // endOfSentence points to        // the last letter 'e'of word 'practice'        // header points to the space(' ')        // which is next to word 'practice'         // If header is null then there is only        // one word in the given sentance        // so set header to the        // first/wordStartPosition node and return.        if (header == null)        {            header = wordStartPosition;            return header;        }         do        {             // Swapping the space ie.            // convert 'practice<space>' to            //'<space>practice'             // store the node which is next to space(' ')            // 'm' which is the first letter of the word 'make'            Node temp = header.Next;            header.Next = wordStartPosition;            wordStartPosition = header;            header = temp;             Node prev = null;                         // Setting sentenceStartPosition to node 'm'            //(first letter of the word 'make')            sentenceStartPosition = header;             // Again Navigate the linked list until            // a space(' ') is found or            // header == null end of the linked list            while (header != null && header.Data != ' ')            {                prev = header;                header = header.Next;            }             // When the next space is found,            // change the pointer to point the previous space            // ie. the word is being converted to            // "m->a->k->e->s-> ->p->r->a->c->t->i->c->e"            prev.Next = wordStartPosition;             // Newly found space will point to            //'m' first letter of the word 'make'            wordStartPosition = sentenceStartPosition;            if (header == null)                break;             // Repeat the loop until            // the end of the linked list is reached        }                 while (header != null);        header = sentenceStartPosition;         // Set the last node's next to null        // ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null        endOfSentence.Next = null;        return header;    }     // Function to print the Linked List    private static void PrintList(Node Header)    {        Node temp = Header;                 // Navigate till the end and print        // the data in each node        while (temp != null)        {            Console.Write(temp.Data);            temp = temp.Next;        }    }     // Driver code    public static void Main(String[] args)    {        String s = "practice makes a man perfect";         // Convert given string to a linked list        // with character as data in each node        Node header = CreateList(s);         Console.WriteLine("Before:");        PrintList(header);         header = Reverse(header);         Console.WriteLine("\nAfter:");        PrintList(header);    }} // This code is contributed by Rajput-Ji
Before:
practice makes a man perfect
After:
perfect man a makes practice
 
Rajput-Ji
clintra
Reverse
Linked List
Strings
Linked List
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Program to implement Singly Linked List in C++ using class
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types