feat: added a function to get the size of a linked list (#763)

* feat: added a function to get the size of a linked list

* Update get_size_of_linked_list.cpp

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
floan 2020-05-19 09:59:38 +05:00 committed by GitHub
parent de65e2b256
commit f4eacb3fd7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,36 @@
#include <iostream>
class Node {
public:
int val;
Node *next;
Node(int v, Node *n) : val(v), next(n) {} // Default constructor for Node
};
int getSize(Node *root) {
if (root == NULL) {
return 0;
}
// Each node will return 1 so the total adds up to be the size
return 1 + getSize(root->next);
}
int main() {
Node *myList = new Node(0, NULL); // Initializes the LinkedList
Node *temp = myList;
// Creates a linked lists of total size 10, numbered 1 - 10
for (int i = 1; i < 10; i++) {
temp->next = new Node(i, NULL);
temp = temp->next;
}
// Creating other lists for checking purposes
Node *secondList = new Node(0, NULL); // List of size 1
Node *thirdList = NULL; // List of size 0
std::cout << getSize(myList) << std::endl
<< getSize(secondList) << std::endl
<< getSize(thirdList) << std::endl;
return 0;
}