TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
get_size_of_linked_list.cpp
1
#include <iostream>
2
3
class
Node
{
4
public
:
5
int
val;
6
Node
*next;
7
8
Node
(
int
v,
Node
*n) : val(v), next(n) {}
// Default constructor for Node
9
};
10
11
int
getSize(
Node
*root) {
12
if
(root == NULL) {
13
return
0;
14
}
15
// Each node will return 1 so the total adds up to be the size
16
return
1 + getSize(root->next);
17
}
18
19
/*
20
* @brief This function dealocates memory related to the given list
21
* It recursively deletes all of the nodes of the input list.
22
* @param room the root/head of the input list
23
* @warning Plese note that the memory for each node has to be alocated using new.
24
*/
25
void
deleteList(
Node
*
const
root) {
26
if
(root != NULL)
27
{
28
deleteList(root->next);
29
delete
root;
30
}
31
}
32
33
int
main
() {
34
Node
*myList =
new
Node
(0, NULL);
// Initializes the LinkedList
35
Node
*temp = myList;
36
// Creates a linked lists of total size 10, numbered 1 - 10
37
for
(
int
i = 1; i < 10; i++) {
38
temp->next =
new
Node
(i, NULL);
39
temp = temp->next;
40
}
41
// Creating other lists for checking purposes
42
Node
*secondList =
new
Node
(0, NULL);
// List of size 1
43
Node
*thirdList = NULL;
// List of size 0
44
45
std::cout << getSize(myList) << std::endl
46
<< getSize(secondList) << std::endl
47
<< getSize(thirdList) << std::endl;
48
deleteList(secondList);
49
deleteList(myList);
50
51
return
0;
52
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
Node
Definition
linkedlist_implentation_usingarray.cpp:14
operations_on_datastructures
get_size_of_linked_list.cpp
Generated by
1.12.0