A linked list is a common data structure made of a chain of nodes in which each node contains a value and a pointer to the next node in the chain.
The head pointer points to the first node, and the last element of the list points to null. When the list is empty, the head pointer points to null.
Before implementing the logic of printing the odd numbers, we need to devise a plan to identify them.
We all know that all even numbers are divisible by ; therefore, they yield a remainder of . We can further this to realize that odd numbers, when divided by , will produce a remainder of .
This difference of remainders can be exploited to differentiate between odd and even groups of numbers.
The modulo operator helps us generate the remainder when one number is divided by another. Here is a list of modulo operators in different languages. For the rest of this article, we will use %, the modulo operator for C++.
To print the odd numbers in data you need to:
Here is a sample code:
void LinkedList::displayOdd()
{
//variable to traverse linked list
node* dummy = head;
do
{
int tempData = dummy->data;
if (tempData % 2 == 1)
{
std::cout << "data: " << tempData << endl;
}
dummy = dummy->next;
} while (dummy != NULL);
}
Run the code cell below to observe the results.
struct node{int data;node* next;};class LinkedList{private:node* head;public://ConstructorLinkedList();//Add elementbool insertAtTail(int element);//Display linked listvoid display();//Display odd datavoid displayOddData();};
To print the odd number nodes you need to:
Here is a sample code:
void LinkedList::displayOddNodes()
{
// mainting a counter
int counter = 0;
//variable to traverse linked list
node* dummy = head;
do
{
//condition to check odd
if (counter % 2 == 1)
{
std::cout << "data: " << dummy->data << endl;
}
//incrementing counter
counter++;
//jumping to next node
dummy = dummy->next;
} while (dummy != NULL);
}
Run the code cell below to observe the results.
#include "LinkedList.h"LinkedList::LinkedList(){head = NULL;}bool LinkedList::insertAtTail(int element){node* newNode = new node;newNode->next = NULL;newNode->data = element;if(head == NULL){head = newNode;}else{node* tail = head;while(tail->next != NULL){tail = tail->next;}tail->next = newNode;}}void LinkedList::display(){//variable to traverse linked listnode* dummy = head;do{std::cout << "data: " << dummy->data << endl;dummy = dummy->next;} while (dummy != NULL);}void LinkedList::displayOddNodes(){// mainting a counterint counter = 0;//variable to traverse linked listnode* dummy = head;do{//condition to check oddif (counter % 2 == 1){std::cout << "data: " << dummy->data << endl;}//incrementing countercounter++;//jumping to next nodedummy = dummy->next;} while (dummy != NULL);}
Free Resources