
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 Linked List Using Iterative Method in C
In this problem, program must print the alternates from the given linked list that is leaving one printing other and so on using iterative method.
Iterative method is the one which generally uses loops that are executed till the condition holds value 1 or true.
Let’s say, list contains the nodes 29, 34, 43, 56 and 88 and than the output will be the alternate nodes such as 29, 43 and 88.
Example
Input: 29->34->43->56->88 Output: 29 43 88
The approach is to traverse the entire list till the last node. While, traversing a counter variable can be taken which is incremented to 1 and value is printed when the counter is even or odd depending upon user’s choice. If the user wants it to display from the 0 than the counter with even value is displayed else the counter with odd value is displayed.
The below code shows the c implementation of the algorithm given.
Algorithm
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> Declare Function void alternate(struct node* head) Set int count = 0 Loop While (head != NULL) IF count % 2 = 0 Print head->data Set count++ Set head = head->next End Step 3 -> Declare Function void push(struct node** header, int newdata) Create newnode using malloc function Set newnode->data = newdata Set newnode->next = (*header) set (*header) = newnode step 4 -> In Main() create head pointing to first node using struct node* head = NULL Call alternate(head) STOP
Example
#include <stdio.h> #include <stdlib.h> //creating structure of a node struct node { int data; struct node* next; }; //function to find and print alternate node void alternate(struct node* head) { int count = 0; while (head != NULL) { if (count % 2 == 0) printf(" %d ", head->data); count++; head = head->next; } } //pushing element into the list void push(struct node** header, int newdata) { struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = newdata; newnode->next = (*header); (*header) = newnode; } int main() { printf("alternate nodes are :"); struct node* head = NULL; push(&head, 1); //calling push function to push elements in list push(&head, 9); push(&head, 10); push(&head, 21); push(&head, 80); alternate(head); return 0; }
Output
If we run above program then it will generate following output.
alternate nodes are : 80 10 1