Code
#include <iostream>using namespace std;class Node {public:int data;Node *next;};int countNodes(Node *head) {int count = 0;Node *current = head;while (current != NULL) {count++;current = current->next;}return count;}int main() {Node *head = NULL;Node *second = NULL;Node *third = NULL;head = new Node();second = new Node();third = new Node();head->data = 1;head->next = second;second->data = 2;second->next = third;third->data = 3;third->next = NULL;cout << "Number of nodes in linked list: " << countNodes(head) << endl;return 0;}
Output
Number of nodes in linked list: 3
0 Comments
Post a Comment