File tree 1 file changed +40
-6
lines changed
data_structures/linked_list
1 file changed +40
-6
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Linked Lists consists of Nodes.
3
+ Nodes contain data and also may link to other nodes:
4
+ - Head Node: First node, the address of the
5
+ head node gives us access of the complete list
6
+ - Last node: points to null
7
+ """
8
+
9
+ from typing import Any
10
+
11
+
1
12
class Node :
2
- def __init__ (self , item , next ) :
13
+ def __init__ (self , item : Any , next : Any ) -> None :
3
14
self .item = item
4
15
self .next = next
5
16
6
17
7
18
class LinkedList :
8
- def __init__ (self ):
19
+ def __init__ (self ) -> None :
9
20
self .head = None
10
21
self .size = 0
11
22
12
- def add (self , item ) :
23
+ def add (self , item : Any ) -> None :
13
24
self .head = Node (item , self .head )
14
25
self .size += 1
15
26
16
- def remove (self ):
27
+ def remove (self ) -> Any :
17
28
if self .is_empty ():
18
29
return None
19
30
else :
@@ -22,10 +33,33 @@ def remove(self):
22
33
self .size -= 1
23
34
return item
24
35
25
- def is_empty (self ):
36
+ def is_empty (self ) -> bool :
26
37
return self .head is None
27
38
28
- def __len__ (self ):
39
+ def __str__ (self ) -> str :
40
+ """
41
+ >>> linked_list = LinkedList()
42
+ >>> linked_list.add(23)
43
+ >>> linked_list.add(14)
44
+ >>> linked_list.add(9)
45
+ >>> print(linked_list)
46
+ 9 --> 14 --> 23
47
+ """
48
+ if not self .is_empty :
49
+ return ""
50
+ else :
51
+ iterate = self .head
52
+ item_str = ""
53
+ item_list = []
54
+ while iterate :
55
+ item_list .append (str (iterate .item ))
56
+ iterate = iterate .next
57
+
58
+ item_str = " --> " .join (item_list )
59
+
60
+ return item_str
61
+
62
+ def __len__ (self ) -> int :
29
63
"""
30
64
>>> linked_list = LinkedList()
31
65
>>> len(linked_list)
You can’t perform that action at this time.
0 commit comments