Count nodes in Linked List

We will insert all element of linked list in beginning & then simply traverse the linked list and keep counter to count the length. At last we will return that counter.

 

Structure and Function : 

 

#include<iostream>
using namespace std;

class node
{
  public:
  int data;
  node* next;
};

void push(node** head_ref, int new_data)
{
  node* new_node = new node();
  new_node->data = new_data;
  new_node->next = *head_ref;
  *head_ref = new_node;
}

int count(node* Node)
{
  int c = 0;
  while(Node != NULL)
  {
    Node = Node->next;
    c++;
  }
  return c;
}

 

Main code : 

 

int main()
{
  int n1, n2, n3, n4, d;
  cin >> n1 >> n2 >> n3 >> n4;
  node* head = NULL;
  push(&head, n1);
  push(&head, n2);
  push(&head, n3);
  push(&head, n4);
  d = count(head);
  cout << d;
  return 0;
}

 

Other Resources : Data Structures, Algorithms, Competitive Coding, Development

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.