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:
Segregate even and odd nodes in a Linked List
Next article icon

Append odd position nodes in reverse at the end of even positioned nodes in a Linked List

Last Updated : 13 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order.

Examples: 

Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL 
Output : 1 -> 3 -> 5 -> 6 -> 4 -> 2 -> NULL

Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL 
Output : 1 -> 3 -> 5 -> 4 -> 2 -> NULL 

Source: Microsoft Interview 

Approach: 

A similar problem has been discussed in the given link, but there the even part was not reversed. Maintains two-pointers odd and even for current nodes at odd and even positions respectively. Also, store the first node of the even linked list so that we can attach the even list at the end of the odd list after all odd and even nodes are connected together in two different lists. Once the even list has been separated, we just need to reverse it. Reversing a linked list can be found here. Once the even list is reversed, attach it to the odd linked list. 

Below is the implementation of the above approach: 

C++




// C++ program to Append odd position nodes
// in reverse at the end of even
// positioned nodes in a Linked List
#include <bits/stdc++.h>
using namespace std;
 
// Linked List Node
struct Node {
    int data;
    struct Node* next;
};
 
// A utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->data = key;
    temp->next = NULL;
    return temp;
}
 
// Rearranges given linked list such that all even
// positioned nodes are before odd positioned
// in a reverse
Node* rearrangeEvenOdd(Node* head)
{
    // Corner case
    if (head == NULL)
        return NULL;
 
    // Initialize first nodes of even and
    // odd lists
    Node* odd = head;
    Node* even = head->next;
 
    // Remember the first node of even list so
    // that we can connect the even list at the
    // end of odd list.
    Node* evenFirst = even;
 
    while (1) {
 
        // If there are no more nodes, then connect
        // first node of even list to the last node
        // of odd list
        if (!odd || !even || !(even->next)) {
            break;
        }
 
        // Connecting odd nodes
        odd->next = even->next;
        odd = even->next;
 
        // If there are NO more even nodes after
        // current odd.
        if (odd->next == NULL) {
            even->next = NULL;
            break;
        }
 
        // Connecting evenevenFirs nodes
        even->next = odd->next;
        even = odd->next;
    }
 
    // Reversal of even linked list
    Node* current = evenFirst;
    Node* prev = NULL;
    Node* front = NULL;
 
    // Iterate in the complete linked list
    while (current != NULL) {
        front = current->next;
        current->next = prev;
        prev = current;
        current = front;
    }
 
    evenFirst = prev;
 
    // Attach the reversed even linked
    // list to odd linked list
    odd->next = evenFirst;
    return head;
}
 
// A utility function to print a linked list
void printlist(Node* node)
{
    while (node != NULL) {
        cout << node->data << " -> ";
        node = node->next;
    }
    cout << "NULL" << endl;
}
 
// Driver code
int main(void)
{
    Node* head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
 
    head = rearrangeEvenOdd(head);
 
    printlist(head);
 
    return 0;
}
 
 

Java




// Java program to Append odd position nodes
// in reverse at the end of even
// positioned nodes in a Linked List
class sol
{
 
// Linked List Node
static class Node
{
    int data;
    Node next;
};
 
// A utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.data = key;
    temp.next = null;
    return temp;
}
 
// Rearranges given linked list such that all even
// positioned nodes are before odd positioned
// in a reverse
static Node rearrangeEvenOdd(Node head)
{
    // Corner case
    if (head == null)
        return null;
 
    // Initialize first nodes of even and
    // odd lists
    Node odd = head;
    Node even = head.next;
 
    // Remember the first node of even list so
    // that we can connect the even list at the
    // end of odd list.
    Node evenFirst = even;
 
    while (true)
    {
 
        // If there are no more nodes, then connect
        // first node of even list to the last node
        // of odd list
        if (odd == null || even == null || (even.next) == null)
        {
            break;
        }
 
        // Connecting odd nodes
        odd.next = even.next;
        odd = even.next;
 
        // If there are NO more even nodes after
        // current odd.
        if (odd.next == null)
        {
            even.next = null;
            break;
        }
 
        // Connecting evenevenFirs nodes
        even.next = odd.next;
        even = odd.next;
    }
 
    // Reversal of even linked list
    Node current = evenFirst;
    Node prev = null;
    Node front = null;
 
    // Iterate in the complete linked list
    while (current != null)
    {
        front = current.next;
        current.next = prev;
        prev = current;
        current = front;
    }
 
    evenFirst = prev;
 
    // Attach the reversed even linked
    // list to odd linked list
    odd.next = evenFirst;
    return head;
}
 
// A utility function to print a linked list
static void printlist(Node node)
{
    while (node != null)
    {
        System.out.print( node.data + " -> ");
        node = node.next;
    }
    System.out.println( "null" );
}
 
// Driver code
public static void main(String args[])
{
    Node head = newNode(1);
    head.next = newNode(2);
    head.next.next = newNode(3);
    head.next.next.next = newNode(4);
    head.next.next.next.next = newNode(5);
    head.next.next.next.next.next = newNode(6);
 
    head = rearrangeEvenOdd(head);
 
    printlist(head);
 
}
}
 
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 program to Append odd position nodes
# in reverse at the end of even
# positioned nodes in a Linked List
import math
 
# Linked List Node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# A utility function to create a new node
def newNode(key):
    temp = Node(key)
    temp.data = key
    temp.next = None
    return temp
 
# Rearranges given linked list such that
# all even positioned nodes are before
# odd positioned in a reverse
def rearrangeEvenOdd(head):
     
    # Corner case
    if (head == None):
        return None
 
    # Initialize first nodes of even and
    # odd lists
    odd = head
    even = head.next
 
    # Remember the first node of even list so
    # that we can connect the even list at the
    # end of odd list.
    evenFirst = even
 
    while True:
 
        # If there are no more nodes,
        # then connect first node of
        # even list to the last node
        # of odd list
        if (odd == None or even == None or
                    (even.next) == None):
            break
     
        # Connecting odd nodes
        odd.next = even.next
        odd = even.next
 
        # If there are NO more even nodes after
        # current odd.
        if (odd.next == None):
            even.next = None
            break
         
        # Connecting evenevenFirs nodes
        even.next = odd.next
        even = odd.next
     
    # Reversal of even linked list
    current = evenFirst
    prev = None
    front = None
 
    # Iterate in the complete linked list
    while (current != None):
        front = current.next
        current.next = prev
        prev = current
        current = front
     
    evenFirst = prev
 
    # Attach the reversed even linked
    # list to odd linked list
    odd.next = evenFirst
    return head
 
# A utility function to print a linked list
def printlist(node):
    while (node != None) :
        print(node.data, end = "->")
        node = node.next
     
    print("NULL")
 
# Driver code
if __name__=='__main__':
    head = newNode(1)
    head.next = newNode(2)
    head.next.next = newNode(3)
    head.next.next.next = newNode(4)
    head.next.next.next.next = newNode(5)
    head.next.next.next.next.next = newNode(6)
 
    head = rearrangeEvenOdd(head)
 
    printlist(head)
 
# This code is contributed by Srathore
 
 

C#




// C# program to Append odd position nodes
// in reverse at the end of even
// positioned nodes in a Linked List
using System;
     
class GFG
{
 
// Linked List Node
public class Node
{
    public int data;
    public Node next;
};
 
// A utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.data = key;
    temp.next = null;
    return temp;
}
 
// Rearranges given linked list such that
// all even positioned nodes are before
// odd positioned in a reverse
static Node rearrangeEvenOdd(Node head)
{
    // Corner case
    if (head == null)
        return null;
 
    // Initialize first nodes of even and
    // odd lists
    Node odd = head;
    Node even = head.next;
 
    // Remember the first node of even list so
    // that we can connect the even list at the
    // end of odd list.
    Node evenFirst = even;
 
    while (true)
    {
 
        // If there are no more nodes, 
        // then connect first node of
        // even list to the last node
        // of odd list
        if (odd == null || even == null ||
                          (even.next) == null)
        {
            break;
        }
 
        // Connecting odd nodes
        odd.next = even.next;
        odd = even.next;
 
        // If there are NO more even nodes after
        // current odd.
        if (odd.next == null)
        {
            even.next = null;
            break;
        }
 
        // Connecting evenevenFirs nodes
        even.next = odd.next;
        even = odd.next;
    }
 
    // Reversal of even linked list
    Node current = evenFirst;
    Node prev = null;
    Node front = null;
 
    // Iterate in the complete linked list
    while (current != null)
    {
        front = current.next;
        current.next = prev;
        prev = current;
        current = front;
    }
 
    evenFirst = prev;
 
    // Attach the reversed even linked
    // list to odd linked list
    odd.next = evenFirst;
    return head;
}
 
// A utility function to print a linked list
static void printlist(Node node)
{
    while (node != null)
    {
        Console.Write( node.data + " -> ");
        node = node.next;
    }
    Console.WriteLine( "null" );
}
 
// Driver code
public static void Main(String []args)
{
    Node head = newNode(1);
    head.next = newNode(2);
    head.next.next = newNode(3);
    head.next.next.next = newNode(4);
    head.next.next.next.next = newNode(5);
    head.next.next.next.next.next = newNode(6);
 
    head = rearrangeEvenOdd(head);
 
    printlist(head);
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// JavaScript program to Append odd position nodes
// in reverse at the end of even
// positioned nodes in a Linked List
 
    // Linked List Node
    class Node {
        constructor() {
            this.data = 0;
            this.next = null;
        }
    }
    // A utility function to create a new node
    function newNode(key) {
    var temp = new Node();
        temp.data = key;
        temp.next = null;
        return temp;
    }
 
    // Rearranges given linked list such that all even
    // positioned nodes are before odd positioned
    // in a reverse
    function rearrangeEvenOdd(head) {
        // Corner case
        if (head == null)
            return null;
 
        // Initialize first nodes of even and
        // odd lists
        var odd = head;
        var even = head.next;
 
        // Remember the first node of even list so
        // that we can connect the even list at the
        // end of odd list.
        var evenFirst = even;
 
        while (true) {
 
            // If there are no more nodes, then connect
            // first node of even list to the last node
            // of odd list
            if (odd == null || even == null ||
            (even.next) == null)
            {
                break;
            }
 
            // Connecting odd nodes
            odd.next = even.next;
            odd = even.next;
 
            // If there are NO more even nodes after
            // current odd.
            if (odd.next == null) {
                even.next = null;
                break;
            }
 
            // Connecting evenevenFirs nodes
            even.next = odd.next;
            even = odd.next;
        }
 
        // Reversal of even linked list
        var current = evenFirst;
        var prev = null;
        var front = null;
 
        // Iterate in the complete linked list
        while (current != null) {
            front = current.next;
            current.next = prev;
            prev = current;
            current = front;
        }
 
        evenFirst = prev;
 
        // Attach the reversed even linked
        // list to odd linked list
        odd.next = evenFirst;
        return head;
    }
 
    // A utility function to print a linked list
    function printlist(node) {
        while (node != null) {
            document.write(node.data + " -> ");
            node = node.next;
        }
        document.write("Null");
    }
 
    // Driver code
     
        var head = newNode(1);
        head.next = newNode(2);
        head.next.next = newNode(3);
        head.next.next.next = newNode(4);
        head.next.next.next.next = newNode(5);
        head.next.next.next.next.next = newNode(6);
 
        head = rearrangeEvenOdd(head);
 
        printlist(head);
 
// This code is contributed by todaysgaurav
 
</script>
 
 
Output
1 -> 3 -> 5 -> 6 -> 4 -> 2 -> NULL 

Complexity Analysis:

  • Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of nodes in the linked list.
  • Auxiliary Space: O(1), as we are not using any extra space for the string.


Next Article
Segregate even and odd nodes in a Linked List

S

Striver
Improve
Article Tags :
  • DSA
  • Linked List
  • Microsoft
Practice Tags :
  • Microsoft
  • Linked List

Similar Reads

  • Reverse the order of all nodes at even position in given Linked List
    Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing
    10 min read
  • Merge odd and even positioned nodes of two Linked Lists alternately
    Given two linked lists L1 and L2, the task is to print a new list obtained by merging odd position nodes of L1 with the even positioned nodes of L2 alternately. Examples: Input: L1 = 8->5->3->2->10->NULL, L2 = 11->13->1->6->9->NULLOutput: 8->13->3->6->10-
    15 min read
  • Rearrange a linked list such that all even and odd positioned nodes are together
    Given a linked list, the task is to rearrange the list in such a way that all odd positioned nodes are together and all even positioned nodes are together. Examples: Input: 1 -> 2 -> 3 -> 4Output: 1 -> 3 -> 2 -> 4 Input: 10 -> 22 -> 30 -> 43 -> 56 -> 70Output: 10 -
    13 min read
  • Given a linked list, reverse alternate nodes and append at the end
    Given a linked list, reverse alternate nodes and append them to the end of the list. Extra allowed space is O(1) Examples: Input: 1->2->3->4->5->6 Output: 1->3->5->6->4->2 Explanation: Two lists are 1->3->5 and 2->4->6, reverse the 2nd list: 6->4->2. M
    11 min read
  • Segregate even and odd nodes in a Linked List
    Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers. Examples: Input: 17->15->8->12->10->5->4->1->7->6->NULLOutp
    15+ min read
  • Find sum of even and odd nodes in a linked list
    Given a linked list, the task is to find the sum of even and odd nodes in it separately. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 Output: Even Sum = 12 Odd Sum = 16 Input: 5 -> 7 -> 8 -> 10 -> 15 Output: Even Sum = 18 Odd Sum = 27 Approach: Traverse the whole li
    6 min read
  • Difference between sums of odd position and even position nodes for each level of a Binary Tree
    Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.
    8 min read
  • Alternate Odd and Even Nodes in a Singly Linked List
    Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where
    15+ min read
  • Swap first odd and even valued nodes from the beginning and end of a Linked List
    Given a singly Linked List, the task is to swap the first odd valued node from the beginning and the first even valued node from the end of the Linked List. If the list contains node values of a single parity, then no modifications are required. Examples: Input: 4 -> 3 -> 5 -> 2 -> 3 -
    13 min read
  • Print odd positioned nodes of even levels in level order of the given binary tree
    Given a binary tree, the task is to print the odd positioned nodes of even levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output:
    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