fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Node {
  6. public:
  7. int data;
  8. Node* next;
  9.  
  10. Node(int data) {
  11. this->data = data;
  12. next = nullptr;
  13. }
  14. };
  15.  
  16. class LinkedList {
  17. private:
  18. Node* head;
  19.  
  20. public:
  21. LinkedList() {
  22. head = nullptr;
  23. }
  24.  
  25. void append(int data) {
  26. Node* new_node = new Node(data);
  27. if (head == nullptr) {
  28. head = new_node;
  29. } else {
  30. Node* current = head;
  31. while (current->next != nullptr) {
  32. current = current->next;
  33. }
  34. current->next = new_node;
  35. }
  36. }
  37.  
  38. int countNodes() {
  39. int count = 0;
  40. Node* current = head;
  41. while (current != nullptr) {
  42. count++;
  43. current = current->next;
  44. }
  45. return count;
  46. }
  47. };
  48.  
  49. int main() {
  50. LinkedList list;
  51.  
  52. list.append(1);
  53. list.append(2);
  54. list.append(3);
  55. list.append(4);
  56. list.append(5);
  57.  
  58. int nodeCount = list.countNodes();
  59. cout << "Number of nodes in the linked list: " << nodeCount << endl;
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5448KB
stdin
Standard input is empty
stdout
Number of nodes in the linked list: 5