#include <iostream> using namespace std; struct node { int data; struct node* next; }; // Function to count nodes in the linked list void count_of_nodes(struct node* head) { int count = 0; // intial point struct node* ptr = head; // Initialize ptr to head if (head == NULL) { cout << "Linked list is empty" << endl; return; } while (ptr != NULL) { count++; ptr = ptr->next; // Move to the next node } cout << "Count of nodes: " << count << endl; } int main() { // Create the head node node* head = new node; head->data = 10; head->next = NULL; cout << "1st node is " << head->data << endl; // Create the second node node* second = new node; second->data = 20; second->next = NULL; head->next = second; cout << "2nd node is " << second->data << endl; // Create the third node node* third = new node; third->data = 30; third->next = NULL; head->next->next = third; // Link second to third cout << "3rd node is " << third->data << endl; // Count the nodes count_of_nodes(head); // Clean up allocated memory delete head; delete second; delete third; return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter