MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / LinkedList

Class LinkedList

data_structures/linked_list/singly_linked_list.py:40–363  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

38
39
40class LinkedList:
41 def __init__(self):
42 """
43 Create and initialize LinkedList class instance.
44 >>> linked_list = LinkedList()
45 >>> linked_list.head is None
46 True
47 """
48 self.head = None
49
50 def __iter__(self) -> Iterator[Any]:
51 """
52 This function is intended for iterators to access
53 and iterate through data inside linked list.
54 >>> linked_list = LinkedList()
55 >>> linked_list.insert_tail("tail")
56 >>> linked_list.insert_tail("tail_1")
57 >>> linked_list.insert_tail("tail_2")
58 >>> for node in linked_list: # __iter__ used here.
59 ... node
60 'tail'
61 'tail_1'
62 'tail_2'
63 """
64 node = self.head
65 while node:
66 yield node.data
67 node = node.next_node
68
69 def __len__(self) -> int:
70 """
71 Return length of linked list i.e. number of nodes
72 >>> linked_list = LinkedList()
73 >>> len(linked_list)
74 0
75 >>> linked_list.insert_tail("tail")
76 >>> len(linked_list)
77 1
78 >>> linked_list.insert_head("head")
79 >>> len(linked_list)
80 2
81 >>> _ = linked_list.delete_tail()
82 >>> len(linked_list)
83 1
84 >>> _ = linked_list.delete_head()
85 >>> len(linked_list)
86 0
87 """
88 return sum(1 for _ in self)
89
90 def __repr__(self) -> str:
91 """
92 String representation/visualization of a Linked Lists
93 >>> linked_list = LinkedList()
94 >>> linked_list.insert_tail(1)
95 >>> linked_list.insert_tail(3)
96 >>> linked_list.__repr__()
97 '1 -> 3'

Callers 3

test_singly_linked_listFunction · 0.70
mainFunction · 0.70

Calls

no outgoing calls

Tested by 2

test_singly_linked_listFunction · 0.56