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:
Print reverse of a Linked List without extra space and modifications
Next article icon

Reverse nodes of a linked list without affecting the special characters

Last Updated : 27 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list of alphabets and special characters. Reverse the given linked list without affecting the position of the special characters. 

Examples:  

Input: g -> @ -> e -> # -> e -> $ -> k -> s -> NULL 
Output: s -> @ -> k -> # -> e -> $ -> e -> g -> NULL 
Explanation: Here we can see that in the output the position of special character in not change and also linked list is reverse.

The idea is to traverse the linked list and store the characters excluding the special characters in a temporary array. Again traverse the linked list and copy elements from the array to the nodes of the linked list in a reverse manner.

Below is the step by step algorithm:  

  1. Take a temporary array, TEMP_ARR.
  2. Traverse the linked list and do the following 
    • if the current element is an alphabet, store that element of the linked list to TEMP_ARR.
    • else, increase node pointer by one
  3. Again traverse the linked list from the head and TEMP_ARR from the end and do the following:
    • if the current element is an alphabet, copy the last element of TEMP_ARR to the current linked list node and decrease the current index of TEMP_ARR for the next iteration.
    • else, increase node by one

Below is the implementation of above approach:  

C++
// C++ program to reverse a linked list // without affecting special characters  #include <iostream>  using namespace std;  // Link list node  struct Node {     char data;     struct Node* next; };  // Function to reverse the linked list // without affecting special characters void reverse(struct Node** head_ref, int size) {     struct Node* current = *head_ref;               char TEMP_ARR[size];          int i = 0;          // Traverse the linked list and insert     // linked list elements to TEMP_ARR     while (current != NULL) {         // if the current data is any alphabet than         // store it in to TEMP_ARR         if ((current->data >= 97 && current->data <= 122) ||                  (current->data >= 65 && current->data <= 90)) {             TEMP_ARR[i++] = current->data;             current = current->next;         }         // else increase the node position         else             current = current->next;     }          current = *head_ref;     // Traverse the linked list again     while (current != NULL)      {         // if current character is an alphabet than         // replace the current element in the linked list         // with the last element of the TEMP_ARR         if ((current->data >= 97 && current->data <= 122) ||                  (current->data >= 65 && current->data <= 90)) {             current->data = TEMP_ARR[--i];             current = current->next;         }         // else increase the node         else             current = current->next;     } }  // Function to push a node  void push(struct Node** head_ref, char new_data) {     /* allocate node */     struct Node* new_node = new Node();      /* put in the data */     new_node->data = new_data;      /* link the old list of the new node */     new_node->next = (*head_ref);      /* move the head to point to the new node */     (*head_ref) = new_node; }  /* Function to print linked list */ void printList(struct Node* head) {     struct Node* temp = head;     while (temp != NULL) {         cout << temp->data;         temp = temp->next;     } }  // Driver program to test above function int main() {     /* Start with the empty list */     struct Node* head = NULL;      push(&head, 's');     push(&head, '$');     push(&head, 'k');     push(&head, 'e');     push(&head, 'e');     push(&head, '@');     push(&head, '#');     push(&head, 'g');     push(&head, 'r');     push(&head, 'o');     push(&head, 'f');     push(&head, 's');     push(&head, '$');     push(&head, 'k');     push(&head, 'e');     push(&head, 'e');     push(&head, 'g');      cout << "Given linked list: ";     printList(head);          reverse(&head, 13);          cout << "\nReversed Linked list: ";     printList(head);          return 0; } 
Java
// Java program to reverse a  // linked list without affecting  // special characters class GFG {  // Link list node  public static class Node  {     char data;     Node next; }  // Function to reverse the linked // list without affecting special  // characters static void reverse(Node head_ref,                     int size) { Node current = head_ref;   char TEMP_ARR[] = new char[size];  int i = 0;  // Traverse the linked list  // and insert linked list  // elements to TEMP_ARR while (current != null) {     // if the current data      // is any alphabet than     // store it in to TEMP_ARR     if ((current.data >= 97 &&           current.data <= 122) ||          (current.data >= 65 &&           current.data <= 90))     {         TEMP_ARR[i++] = current.data;         current = current.next;     }          // else increase the node position     else         current = current.next; }  current = head_ref;  // Traverse the linked list again while (current != null)  {     // if current character is an      // alphabet than replace the      // current element in the linked     // list with the last element      // of the TEMP_ARR     if ((current.data >= 97 &&           current.data <= 122) ||          (current.data >= 65 &&           current.data <= 90))      {         current.data = TEMP_ARR[--i];         current = current.next;     }          // else increase the node     else         current = current.next;     } }  // Function to push a node  static Node push(Node head_ref,                  char new_data) {     /* allocate node */     Node new_node = new Node();      /* put in the data */     new_node.data = new_data;      /* link the old list        off the new node */     new_node.next = (head_ref);      /* move the head to point         to the new node */     (head_ref) = new_node;          return head_ref; }  /* Function to print linked list */ static void printList(Node head) {     Node temp = head;     while (temp != null)      {         System.out.print(temp.data);         temp = temp.next;     } }  // Driver Code public static void main(String rags[]) {     /* Start with the empty list */     Node head = null;      head = push(head, 's');     head = push(head, '$');     head = push(head, 'k');     head = push(head, 'e');     head = push(head, 'e');     head = push(head, '@');     head = push(head, '#');     head = push(head, 'g');     head = push(head, 'r');     head = push(head, 'o');     head = push(head, 'f');     head = push(head, 's');     head = push(head, '$');     head = push(head, 'k');     head = push(head, 'e');     head = push(head, 'e');     head = push(head, 'g');      System.out.print( "Given linked list: ");     printList(head);          reverse(head, 13);          System.out.print("\nReversed Linked list: ");     printList(head); } }  // This code is contributed by Arnab Kundu 
Python3
# Python3 program to reverse a linked list # without affecting special characters  # Link list node class Node:          def __init__(self, x):                  self.data = x         self.next = None  # Function to reverse the linked list # without affecting special characters def reverse(head_ref, size):          current = head_ref     TEMP_ARR = [0 for i in range(256)]      i = 0      # Traverse the linked list and insert     # linked list elements to TEMP_ARR     while (current != None):                  # If the current data is any alphabet than         # store it in to TEMP_ARR         if ((ord(current.data) >= 97 and               ord(current.data) <= 122) or             (ord(current.data) >= 65 and               ord(current.data) <= 90)):             TEMP_ARR[i]= current.data             i += 1             current = current.next                      # Else increase the node position         else:             current = current.next      current = head_ref          # Traverse the linked list again     while (current != None):                  # If current character is an alphabet         # than replace the current element in          # the linked list with the last element         # of the TEMP_ARR         if ((ord(current.data) >= 97 and              ord(current.data) <= 122) or              (ord(current.data) >= 65 and               ord(current.data) <= 90)):             i = i - 1             current.data = TEMP_ARR[i]             current = current.next                      # Else increase the node         else:             current = current.next                  return head_ref  # Function to push a node def push(head_ref, new_data):          # Allocate node      #new_node = (struct Node*)malloc(sizeof(struct Node));      # Put in the data      new_node = Node(new_data)      # Link the old list of the new node      new_node.next = head_ref      # Move the head to point to the new node      head_ref = new_node      return head_ref  # Function to print linked list  def printList(head):          temp = head          while (temp != None):         print(temp.data, end = "")         temp = temp.next  # Driver code if __name__ == '__main__':          # Start with the empty list      head = None      head = push(head, 's')     head = push(head, '$')     head = push(head, 'k')     head = push(head, 'e')     head = push(head, 'e')     head = push(head, '@')     head = push(head, '#')     head = push(head, 'g')     head = push(head, 'r')     head = push(head, 'o')     head = push(head, 'f')     head = push(head, 's')     head = push(head, '$')     head = push(head, 'k')     head = push(head, 'e')     head = push(head, 'e')     head = push(head, 'g')      print("Given linked list: ", end = "")     printList(head)      head = reverse(head, 13)      print("\nReversed Linked list: ", end = "")     printList(head)  # This code is contributed by mohit kumar 29 
C#
// C# program to reverse a  // linked list without affecting  // special characters using System;  class GFG {      // Link list node      public class Node      {         public char data;         public Node next;     }      // Function to reverse the linked     // list without affecting special      // characters     static void reverse(Node head_ref,                         int size)     {         Node current = head_ref;          char []TEMP_ARR = new char[size];          int i = 0;          // Traverse the linked list          // and insert linked list          // elements to TEMP_ARR         while (current != null)         {             // if the current data              // is any alphabet than             // store it in to TEMP_ARR             if ((current.data >= 97 &&                  current.data <= 122) ||                  (current.data >= 65 &&                  current.data <= 90))             {                 TEMP_ARR[i++] = current.data;                 current = current.next;             }              // else increase the node position             else                 current = current.next;         }          current = head_ref;          // Traverse the linked list again         while (current != null)          {             // if current character is an              // alphabet than replace the              // current element in the linked             // list with the last element               // of the TEMP_ARR             if ((current.data >= 97 &&                  current.data <= 122) ||                  (current.data >= 65 &&                  current.data <= 90))              {                 current.data = TEMP_ARR[--i];                 current = current.next;             }              // else increase the node             else                 current = current.next;         }     }      // Function to push a node      static Node push(Node head_ref,                     char new_data)     {         /* allocate node */         Node new_node = new Node();          /* put in the data */         new_node.data = new_data;          /* link the old list         off the new node */         new_node.next = (head_ref);          /* move the head to point          to the new node */         (head_ref) = new_node;          return head_ref;     }      /* Function to print linked list */     static void printList(Node head)     {         Node temp = head;         while (temp != null)          {             Console.Write(temp.data);             temp = temp.next;         }     }      // Driver Code     public static void Main(String []rags)     {         /* Start with the empty list */         Node head = null;          head = push(head, 's');         head = push(head, '$');         head = push(head, 'k');         head = push(head, 'e');         head = push(head, 'e');         head = push(head, '@');         head = push(head, '#');         head = push(head, 'g');         head = push(head, 'r');         head = push(head, 'o');         head = push(head, 'f');         head = push(head, 's');         head = push(head, '$');         head = push(head, 'k');         head = push(head, 'e');         head = push(head, 'e');         head = push(head, 'g');          Console.Write( "Given linked list: ");         printList(head);          reverse(head, 13);          Console.Write("\nReversed Linked list: ");         printList(head);     } }  // This code has been contributed  // by 29AjayKumar 
JavaScript
<script>  // JavaScript program to reverse a // linked list without affecting // special characters  // Link list node class Node {     constructor()     {         let data,next;     } }  // Function to reverse the linked // list without affecting special // characters function reverse(head_ref,size) {     let current = head_ref;     let TEMP_ARR = new Array(size);   let i = 0;   // Traverse the linked list // and insert linked list // elements to TEMP_ARR while (current != null) {     // if the current data     // is any alphabet than     // store it in to TEMP_ARR     if ((current.data.charCodeAt(0) >= 97 &&          current.data.charCodeAt(0) <= 122) ||         (current.data.charCodeAt(0) >= 65 &&          current.data.charCodeAt(0) <= 90))     {         TEMP_ARR[i++] = current.data;         current = current.next;     }           // else increase the node position     else         current = current.next; }   current = head_ref;   // Traverse the linked list again while (current != null) {     // if current character is an     // alphabet than replace the     // current element in the linked     // list with the last element     // of the TEMP_ARR     if ((current.data.charCodeAt(0) >= 97 &&          current.data.charCodeAt(0) <= 122) ||         (current.data.charCodeAt(0) >= 65 &&          current.data.charCodeAt(0) <= 90))     {         current.data = TEMP_ARR[--i];         current = current.next;     }           // else increase the node     else         current = current.next; } return head_ref;      } // Function to push a node function push(head_ref,new_data) {     /* allocate node */     let new_node = new Node();       /* put in the data */     new_node.data = new_data;       /* link the old list        off the new node */     new_node.next = (head_ref);       /* move the head to point        to the new node */     (head_ref) = new_node;           return head_ref; }  /* Function to print linked list */ function printList(head) {     let temp = head;     while (temp != null)     {         document.write(temp.data);         temp = temp.next;     } }  // Driver Code  /* Start with the empty list */ let head = null;  head = push(head, 's'); head = push(head, '$'); head = push(head, 'k'); head = push(head, 'e'); head = push(head, 'e'); head = push(head, '@'); head = push(head, '#'); head = push(head, 'g'); head = push(head, 'r'); head = push(head, 'o'); head = push(head, 'f'); head = push(head, 's'); head = push(head, '$'); head = push(head, 'k'); head = push(head, 'e'); head = push(head, 'e'); head = push(head, 'g');  document.write( "Given linked list: "); printList(head);  head=reverse(head, 13);  document.write("<br>Reversed Linked list: "); printList(head);           // This code is contributed by unknown2108  </script> 

Output
Given linked list: geek$sforg#@eek$s Reversed Linked list: skee$grofs#@kee$g

Complexity Analysis:

  • Time Complexity : O(N), where N is the total number of nodes in the linked list.
  • Auxiliary Space: O(N) 

Next Article
Print reverse of a Linked List without extra space and modifications

S

Shahnawaz_Ali
Improve
Article Tags :
  • Misc
  • Linked List
  • Data Structures
  • DSA
  • Linked Lists
  • Arrays
Practice Tags :
  • Arrays
  • Data Structures
  • Linked List
  • Misc

Similar Reads

  • Reverse a string without affecting special characters
    Given a string, that contains a special character together with alphabets ('a' to 'z' and 'A' to 'Z'), reverse the string in a way that special characters are not affected. Examples: Input: str = "a,b$c"Output: str = "c,b$a"Explanation: Note that $ and , are not moved anywhere. Only subsequence "abc
    10 min read
  • Print reverse of a Linked List without extra space and modifications
    Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list. Examples: Input: 1->2->3->4->5->NULLOutput: 5 4 3 2 1 Input: 10->5->15->20->24->NULLOutput: 24 20 15 5 10 Below are different solutions that are now al
    7 min read
  • Reverse a Doubly Linked List without swapping nodes
    Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (o
    10 min read
  • Reverse alternate K nodes in a Singly Linked List - Iterative Solution
    Given a linked list and an integer K, the task is to reverse every alternate K nodes.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K = 3 Output: 3 2 1 4 5 6 9 8 7Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL, K =
    12 min read
  • Reverse a Linked List according to its Size
    Given a linked list with n nodes, reverse it in the following way : If n is even, reverse it in a group of n/2 nodes.If n is odd, keep the middle node as it is, reverse first n/2 elements and reverse last n/2 elements. Examples: Input : 1 2 3 4 5 6 (n is even) Output : 3 2 1 6 5 4 Input : 1 2 3 4 5
    11 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
  • 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
  • Add two numbers represented by Linked List without any extra space
    Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -> 6 -> 3 -> NULL L2 = 8 -> 4 -> 2 -> NULL Output: 1 ->
    11 min read
  • 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
    6 min read
  • Print reverse of a Linked List without actually reversing
    Given a singly linked list. The task is to print the linked list in reverse order without actually reversing the linked list. Examples: Input: head : 1 -> 2 -> 3 -> 4 -> NULL Output: 4 -> 3 -> 2 -> 1 -> NULL Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5
    8 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