File tree Expand file tree Collapse file tree
data_structures/linked_list Expand file tree Collapse file tree 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+
112class Node :
2- def __init__ (self , item , next ) :
13+ def __init__ (self , item : Any , next : Any ) -> None :
314 self .item = item
415 self .next = next
516
617
718class LinkedList :
8- def __init__ (self ):
19+ def __init__ (self ) -> None :
920 self .head = None
1021 self .size = 0
1122
12- def add (self , item ) :
23+ def add (self , item : Any ) -> None :
1324 self .head = Node (item , self .head )
1425 self .size += 1
1526
16- def remove (self ):
27+ def remove (self ) -> Any :
1728 if self .is_empty ():
1829 return None
1930 else :
@@ -22,10 +33,33 @@ def remove(self):
2233 self .size -= 1
2334 return item
2435
25- def is_empty (self ):
36+ def is_empty (self ) -> bool :
2637 return self .head is None
2738
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 :
2963 """
3064 >>> linked_list = LinkedList()
3165 >>> len(linked_list)
You can’t perform that action at this time.
0 commit comments