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-> ->G->e->e->k->s-> ->f->o->r-> ->G->e->e->k->s
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:
Before: practice makes a man perfect After: perfect man a makes practice
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.