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 Recursion
  • Practice Recursion
  • MCQs on Recursion
  • Recursion Tutorial
  • Recursive Function
  • Recursion vs Iteration
  • Types of Recursions
  • Tail Recursion
  • Josephus Problem
  • Tower of Hanoi
  • Check Palindrome
Open In App
Next Article:
Subtraction of the alternate nodes of Linked List
Next article icon

Print alternate nodes of a linked list using recursion

Last Updated : 29 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list, print alternate nodes of this linked list.

Examples : 

Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9   Input : 10 -> 9 Output : 10

Recursive Approach : 

  1. Initialize a static variable(say flag) 
  2. If flag is odd print the node 
  3. increase head and flag by 1, and recurse for next nodes.

Implementation:

C++




// CPP code to print alternate nodes
// of a linked list using recursion
#include <bits/stdc++.h>
using namespace std;
 
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
 
// Inserting node at the beginning
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
       (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
// Function to print alternate nodes of linked list.
// The boolean flag isOdd is used to find if the current
// node is even or odd.
void printAlternate(struct Node* node, bool isOdd=true)
{
    if (node == NULL)
       return;
    if (isOdd == true)
        cout << node->data << " ";
    printAlternate(node->next, !isOdd);
}
 
// Driver code
int main()
{
    // Start with the empty list
    struct Node* head = NULL;
 
    // construct below list
    // 1->2->3->4->5->6->7->8->9->10
 
    push(&head, 10);
    push(&head, 9);
    push(&head, 8);
    push(&head, 7);
    push(&head, 6);
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
 
    printAlternate(head);
 
    return 0;
}
 
 

Java




// Java code to print alternate nodes
// of a linked list using recursion
class GFG
{
 
// A linked list node
static class Node
{
    int data;
    Node next;
};
 
// Inserting node at the beginning
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to print alternate nodes of linked list.
// The boolean flag isOdd is used to find if the current
// node is even or odd.
static void printAlternate( Node node, boolean isOdd)
{
    if (node == null)
    return;
    if (isOdd == true)
        System.out.print( node.data + " ");
    printAlternate(node.next, !isOdd);
}
 
// Driver code
public static void main(String args[])
{
    // Start with the empty list
    Node head = null;
 
    // construct below list
    // 1.2.3.4.5.6.7.8.9.10
 
    head = push(head, 10);
    head = push(head, 9);
    head = push(head, 8);
    head = push(head, 7);
    head = push(head, 6);
    head = push(head, 5);
    head = push(head, 4);
    head = push(head, 3);
    head = push(head, 2);
    head = push(head, 1);
 
    printAlternate(head,true);
 
}
}
 
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 code to print alternate nodes
# of a linked list using recursion
 
# A linked list node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Inserting node at the beginning
def push( head_ref, new_data):
 
    new_node = Node(new_data);
    new_node.data = new_data;
    new_node.next = head_ref;
    head_ref = new_node;
    return head_ref;
 
# Function to print alternate nodes of
# linked list. The boolean flag isOdd
# is used to find if the current node
# is even or odd.
def printAlternate( node, isOdd):
    if (node == None):
        return;
    if (isOdd == True):
        print( node.data, end = " ");
    if (isOdd == True):
        isOdd = False;
    else:
        isOdd = True;
    printAlternate(node.next, isOdd);
 
# Driver code
 
# Start with the empty list
head = None;
 
# construct below list
# 1->2->3->4->5->6->7->8->9->10
head = push(head, 10);
head = push(head, 9);
head = push(head, 8);
head = push(head, 7);
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
 
printAlternate(head, True);
 
# This code is contributed by 29AjayKumar
 
 

C#




// C# code to print alternate nodes
// of a linked list using recursion
using System;
 
class GFG
{
  
// A linked list node
public class Node
{
    public int data;
    public Node next;
};
  
// Inserting node at the beginning
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
  
// Function to print alternate nodes of linked list.
// The boolean flag isOdd is used to find if the current
// node is even or odd.
static void printAlternate( Node node, bool isOdd)
{
    if (node == null)
    return;
    if (isOdd == true)
        Console.Write( node.data + " ");
    printAlternate(node.next, !isOdd);
}
  
// Driver code
public static void Main(String []args)
{
    // Start with the empty list
    Node head = null;
  
    // construct below list
    // 1.2.3.4.5.6.7.8.9.10
  
    head = push(head, 10);
    head = push(head, 9);
    head = push(head, 8);
    head = push(head, 7);
    head = push(head, 6);
    head = push(head, 5);
    head = push(head, 4);
    head = push(head, 3);
    head = push(head, 2);
    head = push(head, 1);
  
    printAlternate(head,true);
  
}
}
 
// This code has been contributed by 29AjayKumar
 
 

Javascript




<script>
// javascript code to print alternate nodes
// of a linked list using recursion     // A linked list node
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
 
    // Inserting node at the beginning
    function push(head_ref , new_data) {
var new_node = new Node();
        new_node.data = new_data;
        new_node.next = (head_ref);
        (head_ref) = new_node;
        return head_ref;
    }
 
    // Function to print alternate nodes of linked list.
    // The boolean flag isOdd is used to find if the current
    // node is even or odd.
    function printAlternate(node,  isOdd) {
        if (node == null)
            return;
        if (isOdd == true)
            document.write(node.data + " ");
        printAlternate(node.next, !isOdd);
    }
 
    // Driver code
     
        // Start with the empty list
var head = null;
 
        // construct below list
        // 1.2.3.4.5.6.7.8.9.10
 
        head = push(head, 10);
        head = push(head, 9);
        head = push(head, 8);
        head = push(head, 7);
        head = push(head, 6);
        head = push(head, 5);
        head = push(head, 4);
        head = push(head, 3);
        head = push(head, 2);
        head = push(head, 1);
 
        printAlternate(head, true);
 
// This code contributed by umadevi9616
</script>
 
 
Output: 
1 3 5 7 9

 

Time complexity: O(N) where N is no of nodes in linked list
Auxiliary space: O(1), If we consider recursive call stack then it would be O(n)



Next Article
Subtraction of the alternate nodes of Linked List

S

Shahnawaz_Ali
Improve
Article Tags :
  • DSA
  • Linked List
  • Recursion
Practice Tags :
  • Linked List
  • Recursion

Similar Reads

  • Delete a linked list using recursion
    Given a linked list, the task is to delete the linked list using recursion. Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: NULLExplanation: Linked List is Deleted Input: Linked List = 1 -> 12 -> 1 -> 4 -> 1 -> NULL Output: NULLExplanation: Linked L
    5 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
  • Subtraction of the alternate nodes of Linked List
    Given a linked list. The task is to print the difference between the first odd-positioned node with the sum of all other odd-positioned nodes. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : -48 Alternate nodes : 1 -> 3 -> 17 -> 29 1 - (3 + 17 + 29)
    12 min read
  • Sum of the alternate nodes of linked list
    Given a linked list, the task is to print the sum of the alternate nodes of the linked list. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : 50 Alternate nodes : 1 -> 3 -> 17 -> 29 Input : 10 -> 17 -> 33 -> 38 -> 73 Output : 116 Alternat
    12 min read
  • Clone linked list with next and random pointer using Recursion
    Given a linked list of size n where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. The task is to create a clone of this linked list. Approach : The idea is to create a new node corresponding to each node in the original linked list
    8 min read
  • Delete alternate nodes of a Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    14 min read
  • Print the alternate nodes of linked list (Iterative Method)
    Given a linked list, print the alternate nodes of the linked list. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : 1 -> 3 -> 17 -> 29 Alternate nodes : 1 -> 3 -> 17 -> 29 Input : 10 -> 17 -> 33 -> 38 -> 73 Output : 10 -> 33 -
    9 min read
  • An interesting method to print reverse of a linked list
    We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-> 15-> 20-> 25 Output : Reversed Linked list : 25-> 20-> 15-> 5Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85Input : list : 8
    7 min read
  • Delete a Node in a Singly Linked List with Only a Pointer
    Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list. Examples: Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4-
    6 min read
  • Print a singly linked list in spiral order
    Given a Linked list, the task is to print a singly linked list in a spiral fashion, starting from the mid and rotating clockwise. If the linked list has even nodes, then you have to choose the left mid. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> XOutput: 3 -> 4 -> 2 ->
    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