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:
Product of the alternate nodes of linked list
Next article icon

Print the alternate nodes of linked list (Iterative Method)

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

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 -> 73 Alternate nodes : 10 -> 33 -> 73

Approach :

  1. Traverse the whole linked list.
  2. Set count = 0.
  3. Print node when the count is even.
  4. Visit the next node.

Implementation:

C++




// CPP code to print Alternate Nodes
#include <iostream>
using namespace std;
 
/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};
 
/* Function to get the alternate
nodes of the linked list */
void printAlternateNode(struct Node* head)
{
    int count = 0;
 
    while (head != NULL)
    {
 
        // when count is even print the nodes
        if (count % 2 == 0)
            cout  << head->data << " ";
 
        // count the nodes
        count++;
 
        // move on the next node.
        head = head->next;
    }
}
 
// Function to push node at head
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;
}
 
// Driver code
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
 
    /* Use push() function to construct
    the below list 8 -> 23 -> 11 -> 29 -> 12 */
    push(&head, 12);
    push(&head, 29);
    push(&head, 11);
    push(&head, 23);
    push(&head, 8);
 
    printAlternateNode(head);
 
    return 0;
}
 
// This code is contributed by shubhamsingh10
 
 

C




// C code to print Alternate Nodes
#include <stdio.h>
#include <stdlib.h>
 
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Function to get the alternate
   nodes of the linked list */
void printAlternateNode(struct Node* head)
{
    int count = 0;
 
    while (head != NULL) {
 
        // when count is even print the nodes
        if (count % 2 == 0)
            printf(" %d ", head->data);
 
        // count the nodes
        count++;
 
        // move on the next node.
        head = head->next;
    }
}
 
// Function to push node at head
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;
}
 
// Driver code
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
 
    /* Use push() function to construct
       the below list 8 -> 23 -> 11 -> 29 -> 12 */
    push(&head, 12);
    push(&head, 29);
    push(&head, 11);
    push(&head, 23);
    push(&head, 8);
 
    printAlternateNode(head);
 
    return 0;
}
 
 

Java




// Java code to print Alternate Nodes
class GFG
{
     
/* Link list node */
static class Node
{
    int data;
    Node next;
};
 
/* Function to get the alternate
nodes of the linked list */
static void printAlternateNode( Node head)
{
    int count = 0;
 
    while (head != null)
    {
 
        // when count is even print the nodes
        if (count % 2 == 0)
            System.out.printf(" %d ", head.data);
 
        // count the nodes
        count++;
 
        // move on the next node.
        head = head.next;
    }
}
 
// Function to push node at head
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;
}
 
// Driver code
public static void main(String args[])
{
    /* Start with the empty list */
    Node head = null;
 
    /* Use push() function to con
    the below list 8 . 23 . 11 . 29 . 12 */
    head = push(head, 12);
    head = push(head, 29);
    head = push(head, 11);
    head = push(head, 23);
    head = push(head, 8);
 
    printAlternateNode(head);
}
}
 
// This code is contributed by Arnab Kundu
 
 

Python3




# Python3 code to print Alternate Nodes
 
# Link list node
class Node :
     
    def __init__(self, data = None) :
        self.data = data
        self.next = None
     
    # Function to push node at head
    def push(self, data) :
         
        new = Node(data)
        new.next = self
        return new
     
    # Function to get the alternate
    # nodes of the linked list    
    def printAlternateNode(self) :
        head = self
         
        while head and head.next != None :
             
            print(head.data, end = " ")
            head = head.next.next
 
 
# Driver Code       
node = Node()
 
# Use push() function to construct
# the below list 8 -> 23 -> 11 -> 29 -> 12
node = node.push(12)
node = node.push(29)
node = node.push(11)
node = node.push(23)
node = node.push(8)
 
node.printAlternateNode()
 
 

C#




// C# code to print Alternate Nodes
using System;
 
class GFG
{
     
/* Link list node */
public class Node
{
    public int data;
    public Node next;
};
 
/* Function to get the alternate
nodes of the linked list */
static void printAlternateNode( Node head)
{
    int count = 0;
 
    while (head != null)
    {
 
        // when count is even print the nodes
        if (count % 2 == 0)
            Console.Write(" {0} ", head.data);
 
        // count the nodes
        count++;
 
        // move on the next node.
        head = head.next;
    }
}
 
// Function to push node at head
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;
}
 
// Driver code
public static void Main(String []args)
{
    /* Start with the empty list */
    Node head = null;
 
    /* Use push() function to con
    the below list 8 . 23 . 11 . 29 . 12 */
    head = push(head, 12);
    head = push(head, 29);
    head = push(head, 11);
    head = push(head, 23);
    head = push(head, 8);
 
    printAlternateNode(head);
}
}
 
// This code has been contributed by 29AjayKumar
 
 

Javascript




// JavaScript code to print alternate nodes
// link list node
class Node{
    constructor(data){
        this.data = data;
        this.next = null;
    }
}
 
// function to get the alternate
// nodes of the linked list
function printAlternateNode(head){
    let count = 0;
    while(head != null)
    {
     
        // when count is even print the nodes
        if(count % 2 == 0)
            console.log(head.data + " ");
         
        // increment the count
        count++;
         
        // move to the next node
        head = head.next;
    }
}
 
// function to push node at beginning
function push(head_ref, new_data){
    let new_node = new Node(new_data);
    new_node.next = head_ref;
    head_ref = new_node;
    return head_ref;
}
 
// driver code
let head = null;
 
// Use push() function to construct
// the below list 8 -> 23 -> 11 -> 29 -> 12
head = push(head, 12);
head = push(head, 29);
head = push(head, 11);
head = push(head, 23);
head = push(head, 8);
 
printAlternateNode(head);
 
// this code is contributed by Yash Agarwal(yashagarwal2852002)
 
 
Output
8 11 12 

Time Complexity : O(n) 
Auxiliary Space : O(1)

Asked in : Govivace

Efficient Approach(Without using extra variable count):
Follow the below steps to solve the given problem:
1) We simply traverse the linked list but rather moving to the next node we will move next to next node at each time and print the head data.
Below is the implementation of above approach:

C++




// C++ Program to print the alternates nodes
// without using count variable
#include<bits/stdc++.h>
using namespace std;
 
// link list node
struct Node{
    int data;
    Node* next;
    Node(int data){
        this->data = data;
        this->next = NULL;
    }
};
 
// function to get the alternate
// nodes of the linked list
void printAlternateNode(Node* head){
    while(head != NULL){
        cout<<head->data<<" ";
        if(head->next != NULL){
            head = head->next->next;
        }
        else{
            head = head->next;
        }
    }
}
 
// driver program
int main(){
    Node* head = new Node(8);
    head->next = new Node(23);
    head->next->next = new Node(11);
    head->next->next->next = new Node(29);
    head->next->next->next->next = new Node(12);
     
    printAlternateNode(head);
    return 0;
}
 
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)
 
 

Python3




# Python program to print the alternates node
# without using count variable
# link list node
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
     
     
# function to get the alternate
# nodes of the linked list
def printAlternateNode(head):
    while(head is not None):
        print(head.data, end=" ")
        if(head.next is not None):
            head = head.next.next
        else:
            head = head.next
         
 
# driver program
head = Node(8)
head.next = Node(23)
head.next.next = Node(11)
head.next.next.next = Node(29)
head.next.next.next.next = Node(12)
 
printAlternateNode(head)
 
 

Java




// C++ Program to print the alternates nodes
// without using count variable
public class LinkedList {
    Node head;
    // link list node
    static class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
    // function to get the alternate
    // nodes of the linked list
    public void printAlternateNode(Node head)
    {
        while (head != null) {
            System.out.print(head.data + " ");
            if (head.next != null) {
                head = head.next.next;
            }
            else {
                head = head.next;
            }
        }
    }
    // driver program
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
        llist.head = new Node(8);
        Node second = new Node(23);
        Node third = new Node(11);
        Node fourth = new Node(29);
        Node fifth = new Node(12);
        llist.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;
        llist.printAlternateNode(llist.head);
    }
}
 
 

C#




// C# Program to print the alternates nodes
// without using count variable
using System;
 
// link list node
public class Node {
    public int data;
    public Node next;
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}
 
public class Program {
    // function to get the alternate
    // nodes of the linked list
    public static void printAlternateNode(Node head)
    {
        while (head != null) {
            Console.Write(head.data + " ");
            if (head.next != null) {
                head = head.next.next;
            }
            else {
                head = head.next;
            }
        }
    } // driver program
    public static void Main()
    {
        Node head = new Node(8);
        head.next = new Node(23);
        head.next.next = new Node(11);
        head.next.next.next = new Node(29);
        head.next.next.next.next = new Node(12);
 
        printAlternateNode(head);
    }
}
 
 

Javascript




// C++ Program to print the alternates nodes
// without using count variable
// link list node
class Node{
    constructor(data){
        this.data = data;
        this.next = null;
    }
}
 
// function to get the alternate
// nodes of the linked list
function printAlternateNode(head){
    while(head != null){
        console.log(head.data + " ");
        if(head.next != null){
            head = head.next.next;
        }
        else{
            head = head.next;
        }
    }
}
 
// driver program
let head = new Node(8);
head.next = new Node(23);
head.next.next = new Node(11);
head.next.next.next = new Node(29);
head.next.next.next.next = new Node(12);
  
printAlternateNode(head);
 
 
Output
8 11 12 

Time Complexity: O(N) where N is the number of nodes in the Linked List.
Auxiliary Space: O(1)



Next Article
Product of the alternate nodes of linked list

S

shrikanth13
Improve
Article Tags :
  • DSA
  • Linked List
  • Govivace
Practice Tags :
  • Linked List

Similar Reads

  • Product of the alternate nodes of linked list
    Given a linked list, the task is to print the product of alternate nodes of the given linked list. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : 1479 Alternate nodes : 1 -> 3 -> 17 -> 29 Input : 10 -> 17 -> 33 -> 38 -> 73 Output : 2409
    12 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
  • 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
  • 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
  • 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
  • Print nodes of linked list at given indexes
    Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
    15+ 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
  • Insert Node at the End of a Linked List
    Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end
    9 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
  • Print alternate nodes of a linked list using recursion
    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 : Initialize a static variable(say flag) If flag
    6 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