
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Alternate Nodes of a Linked List Using Recursion in C++
A linked list is a linear data structure that stores the element in non-contiguous memory locations. Every element contains a pointer to the next element of the linked list.
Example −
In this problem, we are given a linked list and we need to print the elements of this linked list but only alternate elements are to be printed. Let’s take an example to understand the problem better,
Input : 2 -> 4 -> 1 -> 67 -> 48 -> 90 Output : 2 -> 1 -> 48
Explanation − We will print alternate elements on the linked list. So first, third and fifth elements are printed.
We will use a flag element that will initially be 0 and will be increased at every iteration that prints element otherwise decrease it and we will print the node value when the flag is 0.
Example
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void printAlternateNode(struct Node* head){ int flag = 0; while (head != NULL) { if (flag == 0){ printf(" %d ", head->data); flag = 1; } else flag = 0; head = head->next; } } void insertNode(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; } int main(){ struct Node* head = NULL; insertNode(&head, 23); insertNode(&head, 4); insertNode(&head, 98); insertNode(&head, 5); insertNode(&head, 71); printAlternateNode(head); return 0; }
Output
71 98 23
Advertisements