mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
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:
parent
de65e2b256
commit
f4eacb3fd7
36
operations_on_datastructures/get_size_of_linked_list.cpp
Normal file
36
operations_on_datastructures/get_size_of_linked_list.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user