-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_linked_list.py
More file actions
64 lines (48 loc) · 1.45 KB
/
create_linked_list.py
File metadata and controls
64 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
__author__ = '[Kamil Adamski](https://github.com/adamsqi)'
__date__ = '2020.07.26'
"""
This program creates a linked list and prints the total number of nodes.
Program:
```python
example_elements = [1, 3, 6, 2, 1, 5]
linked_list = LinkedList(example_elements)
linked_list.create()
head_node = linked_list.nodes[0]
linked_list.count_number_of_nodes(head=head_node)
```
Results:
```python
Total number of nodes equals to: 6
```
"""
from typing import List
class Node:
next = None
def __init__(self, data: int):
self.data = data
class LinkedList:
def __init__(self, elements: List[int]):
self.elements = elements
self.nodes = []
self.counter = 0
def create(self) -> None:
for el in self.elements:
node = Node(el)
self.nodes.append(node)
self._connect_nodes()
def _connect_nodes(self) -> None:
for i, node in enumerate(self.nodes[:-1]):
node.next = self.nodes[i + 1]
def count_number_of_nodes(self, head: Node) -> None:
self.counter += 1
if head.next is not None:
self.count_number_of_nodes(head.next)
def main():
example_elements = [1, 3, 6, 2, 1, 5]
linked_list = LinkedList(example_elements)
linked_list.create()
head_node = linked_list.nodes[0]
linked_list.count_number_of_nodes(head=head_node)
print(f'Total number of nodes equals to: {linked_list.counter}')
if __name__ == '__main__':
main()